0

Mongoose (v3.8) + Node.js

I have a model called 'Products' which has this field:

  upvoted_by: [{
    user_id: { type: Schema.ObjectId, ref: 'Users' },
    timestamp: { type: Date }
  }]

And the Users model has a bunch of other fields.

To add an upvote, I do this:

product.upvoted_by.push({
  user_id: req.user,
  timestamp: new Date()
});

I'm trying to populate the upvoted_by.user_id field so that it contains the corresponding user data.

I tried this but it doesn't seem to work:

// product (= a document) has been found before
product.populate('upvoted_by.user_id', {
  select: 'username'    // username is a field in the Users model
}, function(err, doc) {
  console.log(JSON.stringify(doc));
});

Any idea what's going wrong and how to fix it?

KGo
  • 18,536
  • 11
  • 31
  • 47

2 Answers2

3

As per the docs, the following syntax should work, where select is an attribute of the Object passed to the populate method.

product.populate({path:"upvoted_by.user_id",
                  select:"username"}).exec(function(err, doc) {
  console.log(err);
  console.log(JSON.stringify(doc));
});
BatScream
  • 19,260
  • 4
  • 52
  • 68
  • I had to change a few things, but it's close enough! – KGo Jan 06 '15 at 20:35
  • 1
    @KaranGoel, a friendly FYI: if someone takes the time to help you but you essentially post a small tweak and accept that as the answer over their answer (that did solve the issue) it doesn't inspire people to help you (or others) in the future. – Jason Cust May 04 '15 at 14:45
0

I ended up doing this:

product.populate({
  path: 'upvoted_by.user_id',
  select: 'username profile.picture profile.name'}, function(err, doc) {
    console.log(JSON.stringify(doc.upvoted_by));
});
KGo
  • 18,536
  • 11
  • 31
  • 47