Ask Your Question
2

How can I use .populate() in Mongoose to select specific fields?

asked 2021-08-31 11:00:00 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-07-23 00:00:00 +0000

plato gravatar image

To use .populate() in Mongoose to select specific fields, you can pass an object of options as the second argument to the .populate() method. This object should have a 'select' key set to a space-separated list of the fields you want to select.

For example:

User.findOne({ name: 'John' })
  .populate({
    path: 'posts',
    select: 'title date'
  })
  .exec(function(err, user) {
    if (err) throw err;
    console.log(user.posts);
  });

In this example, we are selecting only the 'title' and 'date' fields from the 'posts' collection while populating it.

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: 2021-08-31 11:00:00 +0000

Seen: 10 times

Last updated: Jul 23 '22