如何使用猫鼬中的更新查询来更新文档?

问题描述 投票:0回答:1

这是我在帖子模型中使用的注释密钥对:

likes:[
    user= {
        type:Schema.Types.ObjectId,
        refPath:'onModel'
    }
]

当我尝试通过运行以下命令将对象推到likes数组时,它将失败。过滤器部分工作正常,但更新部分出现了一些问题,最终导致执行catch块。

Post.updateOne({ _id: req.params.postid, "likes": { $ne : { user: 
authorizedData.jwt_payload.patient._id }}},
    { "$set" : { "likes.$.user": "authorizedData.jwt_payload.patient._id" 
}})
    .then(re => res.json(re))
    .catch(err => res.json("already liked")) 

将非常感谢您的帮助。

html node.js mongodb express mongoose
1个回答
0
投票

尝试使用$push聚合,该聚合用于将对象推入mongoDB中的内部数组。您的更新查询应类似于以下内容:

© www.soinside.com 2019 - 2024. All rights reserved.