Ask Your Question
4

How can Mongoose be used to populate an array of objects that contain a reference?

asked 2023-07-21 06:24:16 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-07-21 06:29:01 +0000

huitzilopochtli gravatar image

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.

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2023-07-21 06:24:16 +0000

Seen: 11 times

Last updated: Jul 21 '23