用mogo填充数组



我已经创建了以下Schema:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Player = require('./player');
var gameSchema = new Schema({
  created_at: Date,
  nrOfCards: String,
  players: [{
          sticks: String,
          player: {
              type: mongoose.Schema.Types.ObjectId,
              ref: 'Player'
          }
      }],
});
var Game = mongoose.model('Game', gameSchema);

保存部分工作正常,保存的对象可能看起来像这样:

    "_id": "57dd11aca0c36114588fd250",
    "nrOfCards": "3",
    "__v": 0,
    "players": [
      {
        "_id": "57d415e527c20f3ed2416e05",
        "age": "33"
      },
      {
        "_id": "57d417df2186d53f3d49c996",
        "age": "73"
      },
      {
        "_id": "57d41d85ec315d4234010c7d",
        "age": "20"
      }
    ]
  },

保存一个对象后,我想让它返回与玩家字段填充。下面是我的尝试:

   app.post('/api/games', function(req, res) {
        Game.create({
            players : req.body.activePlayers,
            nrOfCards: req.body.nrOfCards,
        }, function(err, game) {
            if (err) {
              res.send(err);
            } else {
              Game.findOne(game)
                  .populate('players.player')
                  .exec(function (err, newgame) {
                    if (err) return handleError(err);
                    console.log(newgame);
                      res.json(newgame);
                  });
            }
        });
    });

认为.populate('players.player')应该做到这一点,但我收到的是只包含player_id的未填充字段。

欣赏

提示。谢谢!

使用

player: { type: Schema.Types.ObjectId,ref: 'Player' }

相关内容

  • 没有找到相关文章

最新更新