在猫鼬中创建嵌套关联

时间:2018-12-05 21:33:01

标签: node.js mongoose

让我们说我们有这样的模型: 游戏:

const GameSchema = new mongoose.Schema({
    player_1:   { type: mongoose.Schema.Types.ObjectId, ref: 'Player' },
    player_2:   { type: mongoose.Schema.Types.ObjectId, ref: 'Player' },
    name:       { type: String },
    _board:     { type: mongoose.Schema.Types.ObjectId, ref: 'Board' },
});

const Game = mongoose.model('Game',GameSchema); 棋盘,属于游戏:

const BoardSchema = new mongoose.Schema({
    name:   { type: String },
    fields: { type: mongoose.Schema.Types.ObjectId, ref: 'Field' }
});

const Board = mongoose.model('Board', BoardSchema);

module.exports = Board;

和属于董事会的字段:

const FieldSchema = new mongoose.Schema({
    x:      { type: Number },
    y:      { type: Number },
    value:  { type: Boolean },
    _board: { type: mongoose.Schema.Types.ObjectId, ref: 'Board' },
});

const Field = mongoose.model('Field', FieldSchema);

如何创建包含所需字段的新游戏并添加棋盘? 我最初的想法是这样的:

module.exports = (req, res) => {
    Game.create(req.body, (error, game) => {
      var fields = []
      fields.push(Field.create({x: 0, y: 0}))
      fields.push(Field.create({x: 0, y: 1}))
      fields.push(Field.create({x: 0, y: 2}))
      fields.push(Field.create({x: 1, y: 0}))
      fields.push(Field.create({x: 1, y: 1}))
      fields.push(Field.create({x: 1, y: 2}))
      fields.push(Field.create({x: 2, y: 0}))
      fields.push(Field.create({x: 2, y: 1}))
      fields.push(Field.create({x: 2, y: 2}))
      var board = Board.create({fields: fields}, (error, board) => {
        game._board = board
      })
      res.redirect('/games/' + game._id)
    })
}

但它为未解决的承诺而尖叫。然后我尝试使用.then,最后得到一棵非常丑陋的树,甚至没有起作用

0 个答案:

没有答案