1 | initial version |
To populate an array of objects that contain a reference in Mongoose, you can use the populate()
method along with path
and model
options.
Assuming you have two models named Author
and Book
, and Book
has a reference to Author
, here's an example:
const mongoose = require('mongoose');
// Define Author model
const AuthorSchema = new mongoose.Schema({
name: String,
age: Number
});
const Author = mongoose.model('Author', AuthorSchema);
// Define Book model with a reference to Author
const BookSchema = new mongoose.Schema({
title: String,
author: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Author' // reference to Author model
}
});
const Book = mongoose.model('Book', BookSchema);
// Find all books and populate author field
Book.find().populate('author', 'name age').exec((err, books) => {
if (err) {
console.log(err);
} else {
console.log(books);
}
});
In the example above, we're finding all books and populating the author
field with data from the Author
model. The populate()
method takes two parameters: the path
(which is the field to populate), and the model
(which is the reference model to use). We can also specify which fields to include from the referenced model by passing them as a space-separated string after the model
parameter.