如何正确使用.populate方法在猫鼬?

时间:2015-08-30 11:10:14

标签: node.js mongodb mongoose

我有这段代码

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);
                });
            });
        });
    });

从这段代码我得到了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
}
]
}

然后我尝试将这些对象插入一个大文档

我已有的代码

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);
                });
             });
        });
    })

我得到了这个json:

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

你可以看到我根本没有获得用户对象,只有id,与item对象相同。

我认为路径障碍中的问题, Game.populate(游戏,{路径:'用户'} 但我不知道这条道路应该是怎样的。

0 个答案:

没有答案