如何更新嵌套对象

时间:2019-04-07 14:30:36

标签: express vue.js mongoose

我想使用$ push方法将对象推入嵌套数组。但是我无法使其正常工作,您可以动态地在数组内部获取正确的对象。让我通过显示代码来更好地解释。

这是我的架构:

var StartedRaceSchema = new mongoose.Schema({
    waypoints: {
        type: Object,
        name: String,
        check_ins: {
            type: Object,
            user: {
                type: Object,
                ref: 'User'
            }
        }
    }
});

在航点上签入时,必须将其推入嵌套Check_ins的正确航点中

这是更新代码:

StartedRace.findByIdAndUpdate(req.params.id,
        { $push: { 'waypoints.1.check_ins': req.body.user } },
        function (error) {
            if (error) {
                console.log(error)
                res.send({
                    success: false,
                    error: error
                })
            } else {
                res.send({
                    success: true
                })
            }
        }
    )

如您所见,我只能使其与以下字段一起使用:

'waypoints.1.check_ins'

那个1必须是动态的,因为它在参数内发送。 但是我不能让它动态地工作,只能进行硬编码。

有人知道该怎么做吗?

2 个答案:

答案 0 :(得分:0)

使用其ID枚举的check_ins列表填充集合。

  waypoints.check_ins = {
      ...waypoints.check_ins,
      [response.id]: response
  }

您将获得check_ins的列表,可以通过其ID进行引用。

答案 1 :(得分:0)

您可以尝试使用以下语法代替点符号:

    let id = req.params.id;
    StartedRace.findByIdAndUpdate(req.params.id,
      { $push: { waypoints: { id: { check_ins: req.body.user } } } }, { new : true } )
        .exec()
        .then(race => console.log(race))
        .catch(err => err);

我使用了Promise,但在回调中却是相同的。