Populate in mongoose
Situation: In many times, Models need to other model's data.
For example, A 'Book' model needs 'Author' model. In this case we can define author field in Book model. Or we can bring author models using POPULATE method.
If you dont know 'populate' look here "https://mongoosejs.com/docs/populate.html"
How to use populate.
- There is two models : Book, Author
Book ModelSchema
// models/Book.js
var BookSchema = mongoose.Schema({
title: String,
pageQunitity: Number,
publishingCompany: String
}, {
toJSON: { virtuals: true }, // To show populated data, we need to set thse to options
toObject: { virtuals: true } //
});
BookSchema.virtual('author', {
ref: 'Author',
localField: '_id', // this means 'BookSchema._id'
foreignField: 'book' // this means 'models/author.js/ AuthorSchema.book'
});
// The ref option, which tells Mongoose which model to populate documents from.
// The localField and foreignField options. Mongoose will populate documents from the model in ref whose foreignField matches this document's localField.
Author ModelSchame
// models/author.js
var AuthorSchema = mongoose.Schema({
book:{
type: mongoose.Schema.Types.ObjectId,
ref: 'Book',
required: true
},
name: String,
age: Number,
});
Adapting populate in query
We just need to put "populate('author')" when we find datas.
const book = await Book.findById(bookId).populate('author');
response
Before using populate.
{
"success": true,
"data": {
"_id": "5f4674264ec3915394fcc374",
"title": "Real book",
"pageQunitity": 340,
"publishingCompany": "acdc",
}
}
After using populate.
{
"success": true,
"data": {
"_id": "5f4674264ec3915394fcc374",
"title": "Real book",
"pageQunitity": 340,
"publishingCompany": "acdc",
"author": [ // WE GOT 'AUTHOR' DATA !
{
"_id": "5f489aa99866a05b5016212d",
"name": "jordan k",
"age": 20
}
]
}
}
'mongoDB' 카테고리의 다른 글
MongoDB query (0) | 2020.07.22 |
---|