【问题标题】:Updating a child object property of a parent object which needs to be populated in mongoose更新需要在猫鼬中填充的父对象的子对象属性
【发布时间】:2014-05-08 06:22:51
【问题描述】:

我是 Mongoose 的新手,在访问模型更深层次的属性和更新以下模型结构的属性时,我很难理解。

游戏架构

var gameSchema = new Schema({
    opponents: [{
        type: Schema.Types.ObjectId,
        ref: 'teams'
    }],
    startTime: { type: Date, default: Date.now },
    endTime: Date,
    pauses: [{
        start: Date,
        end: Date
    }],
    winner: {
        type: Schema.Types.ObjectId,
        ref: 'teams'
    },
    status: {type: String, default: "created"},
    score: [{
         "opponent1": {type: Number, default: 0},
         "opponent2": {type: Number, default: 0}
    }],

}, { versionKey: false });

团队架构

var teamSchema = new Schema({
    name:String,
    badge:String,
    goals:[{type: Date, default: Date.now}],
    totalWins:Number
}, { versionKey: false });

我的问题是我正在尝试为特定游戏中的团队添加目标。

所以我的终点:

POST:/api/game/GAME_ID/goal

数据:{_id: TEAMID}

我认为以下方法会起作用:

Games.findById(GAME_ID)
        .populate('opponents')
        .find({'opponent._id': TEAM_ID})
        .exec(function(err, team) {
            // Team from game with matching ID returned
            // Now push goal time into array
            team.goal.push(Date.now());
        });

上面似乎没有返回一个团队。如果我删除第二个发现游戏返回,然后我必须做一些像这样可怕的事情:

Games.findById(GAME_ID)
    .populate('opponents')
    .exec(function(err, game) {
         if(game.opponents[0]._id.toString() === req.body._id) {
             game.opponents[0].goals.push(Date.now());
         } else if (game.opponents[1]._id.toString() === req.body._id) {
             game.opponents[1].goals.push(Date.now());
         } else {
             // Throw error no matching team with id
         }
     });

game.save(function(err, game) {
    //Game saved
});

这最后一个例子似乎有效,但是当我尝试添加更多目标时,它会覆盖旧的目标时间。

所以回顾一下。

  • 如何查询 Games 模型以通过 id 检索具有 还没有被填充?
  • 如何设置将目标时间戳推送到目标数组中而不 覆盖前一个?

是否可以比上面给出的当前示例更优雅地执行这些操作。

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:
    Games.findById(GAME_ID)
        .populate(
            path: 'opponents',
            match: { _id: TEAM_ID}
        )
        .exec(function(err, team) {
            // Team from game with matching ID returned
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-25
      • 2013-01-13
      • 2021-08-16
      • 1970-01-01
      • 1970-01-01
      • 2015-05-29
      • 2014-07-28
      相关资源
      最近更新 更多