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.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-07-21 06:24:16 +0000
Seen: 12 times
Last updated: Jul 21 '23
How can I deal with Expression.Error related to a column in Power Query?
How can you implement pagination in Oracle for the LISTAGG() function?
What is the process for implementing a FutureBuilder on an OnTap function in Flutter?
How can we require users to be logged in before they can access the root folders in WordPress?
In SCSS, what is the method for grouping and reusing a set of classes and styles?
How can popen() be used to direct streaming data to TAR?
How does iOS retrieve information from a BLE device?
How can Django Admin accommodate a variety of formats and locales for its input fields?