+ 1
How to access foreign key documents fields in mongoDB mongoose
I have document called book, in book i have librarian_id which is foreign key, and it links book document to librarian document. I want to access first_name field present in librarian document through book document. How can I do that ? Iam using mongoose mongoDB node js
1 Resposta
0
const mongoose = require('mongoose');
// Define the Librarian schema and model
const librarianSchema = new mongoose.Schema({
first_name: String,
// other librarian fields
});
const Librarian = mongoose.model('Librarian', librarianSchema);
// Define the Book schema and model
const bookSchema = new mongoose.Schema({
title: String,
librarian_id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Librarian', // Reference to the Librarian model
},
// other book fields
});
const Book = mongoose.model('Book', bookSchema);
// Example of how to access the librarian's first_name field from a book document
Book.findOne({ title: 'Your Book Title' })
.populate('librarian_id', 'first_name') // Populate the librarian_id field and select only the first_name field
.exec((err, book) => {
if (err) {
console.error(err);
return;
}
console.log('Book Title:', book.title);
console.log('Librarian First Name:', book.librarian_id.first_name);
});