express - 如何更新嵌套对象
问题描述
我想使用 $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 需要是动态的,因为它是在参数中发送的。但我不能让它动态工作,只能硬编码。
有谁知道如何做到这一点?
解决方案
您可以尝试这种语法而不是点符号:
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,但回调也是如此。
推荐阅读
- mysql - 如何在mysql中使用sum、join、order by和where子句?
- c - 始终将 strtok_s 的第一个参数保持为 NULL 是否正确?
- asp.net-core - .NET Core 运行时无需安装
- firebase - Firestore 安全规则 .hasAny(['A', 'B', 'C']) 是否仍然可用?
- android - 无法在我的 Webviewer 中启用 Zoom
- android - CN1 连接 - 公共场所互联网不稳定时的担忧
- batch-file - 如何在 Windows 批处理中正确排列记录?
- java - Java Not Equals String 语法不起作用
- permissions - 具有错误用户/权限的 Pid 文件
- mysql - 根据条件选择列