简体   繁体   English

如何使用多个条件更新mongodb的文档?

[英]How to update document of mongodb using multiple conditions?

I have a post schema that simply has attributes like _id, text, likes and comments.我有一个帖子模式,它只具有_id、文本、喜欢和评论等属性。 I want to push user id into likes array it if fulfills two conditions.如果满足两个条件,我想将用户 id 推送到 likes 数组中。 Firstly the id of the post should match the query param and then the likes array should not already contain the id of the person trying to like the post.首先,帖子的 id 应该与查询参数匹配,然后 likes 数组不应该已经包含试图喜欢帖子的人的 id。 Instead error msg should come: Post already liked.相反,错误消息应该出现:帖子已经喜欢了。

Like key pair from post schema像后架构中的密钥对

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

I wrote the following query but it doesn't work.我写了以下查询,但它不起作用。 The update part works fine but some issue with the first argument.更新部分工作正常,但第一个参数存在一些问题。

Post.update({$and: [{ _id: req.params.postid},{"likes": { $ne : { user: 
authorizedData.jwt_payload.patient._id  }}}]},
            { $push: { likes: {user: authorizedData.jwt_payload.patient._id }}})
            .then(post => res.json(post))
            .catch(err => res.json(err))

Any suggestions please?请问有什么建议吗?

Ok, it can be simple in this way :好的,这可以很简单:

Post.update({
    _id: req.params.postid,
    'likes.user': {
        $ne:
            authorizedData.jwt_payload.patient._id
    }
},
    { $push: { likes: { user: authorizedData.jwt_payload.patient._id } } })
    .then(post => res.json(post))
    .catch(err => res.json(err))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM