首页 > 解决方案 > 如何更新嵌套对象

问题描述

我想使用 $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 需要是动态的,因为它是在参数中发送的。但我不能让它动态工作,只能硬编码。

有谁知道如何做到这一点?

标签: expressvue.jsmongoose

解决方案


您可以尝试这种语法而不是点符号:

    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,但回调也是如此。


推荐阅读