M
M
Misha Kogan2015-08-30 12:25:40
JavaScript
Misha Kogan, 2015-08-30 12:25:40

How to get second level collections with mongoose.populate?

For example, I have this code

app.get('/json', function(req, res) {
        Bet.find({}, function(err, bets){
            if (err) throw err;
            Bet.populate(bets, { path: 'item' }, function(err, bets){
                if(err) throw err;
                Bet.populate(bets, { path: 'user' }, function(err, bets) {
                    if(err) throw err;
                    res.json(bets);
                });
            });
        });
    });

From it I get this json
{
   _id: "55e2ca9cc8b4b71821a6e90f",
   user: {
      _id: "55e2c9c3faa34a6d1f80ee93",
      __v: 0,
   steam: {
             avatar:"jpg",
            username: "Robert House",
          id: "76561198236425518"
         }
    },
itemsCount: 1,
__v: 0,
item: [
     {
       _id: "55e2ca9cc8b4b71821a6e910",
      type: "Rare mount",
     icon_url_large: "icon",
     icon_url: "icon",
     name: "Noctis the Heavenly Qilin Guardian",
      __v: 0
}
]
}

Now I have a goal to bring this kind of objects into one document
with this code:
app.get('/gamesjson', function(req, res) {
        Game.find({}, function(err, games){
            if(err) throw err;
            Game.populate(games, { path: 'bets' }, function(err, games){
                Game.populate(games, { path: 'user' }, function(err, games) {
                    if(err) throw err;
                    res.json(games);
                });
             });
        });
    })

And I get this json
_id: "55e2ca79c8b4b71821a6e90e",
__v: 0,
bets: [
 {
    _id: "55e2ca9cc8b4b71821a6e90f",
     user: "55e2c9c3faa34a6d1f80ee93",
     itemsCount: 1,
    __v: 0,
     item: [
       "55e2ca9cc8b4b71821a6e910"
     ]
  }
 ]
}

But getting the properties of the user and item object does not work anymore, how is the populate method implemented if it is nested further than the first level?
As I understand it, the problem is in the path
Bet.populate(bets, { path: 'user' }, function(err, bets)
But I can't figure out how to specify the path.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Misha Kogan, 2015-08-30
@Kogan4ik

Found the answer here: stackoverflow.com/questions/19222520/populate-nest...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question