简体   繁体   English

猫鼬如何有条件推入嵌套数组

[英]Mongoose How to push to nested array with condition

Suppose I have the following schema: 假设我有以下架构:

{
  userId: docId,
  skills: [
    {
      _id: SkillId,
      endorsers: [
        {
          userId: idOfUser
        }
      ]
    }
  ]
}

What I want is a user should not be able to endorse a specific skill in a document more than once. 我想要的是用户不应多次认可文档中的特定技能。 First should find a specific document using its docId , and inside that, a specific skill using skillId , and then check if its endorsers array is empty or a specific user not endorsed yet, then push. 首先应使用其docId查找特定文档,并在其内部使用skillId特定技能,然后检查其endorsers数组是否为空或尚未认可的特定用户,然后进行推送。 What I tried so far: 到目前为止我尝试过的是:

    {
      "userId": req.params.userId,
      "skills": {
        "$elemMatch": {
          "skillId": ObjectId(req.params.skillId),
          "$or": [
            {"endorsers": []},
            {"endorsers.userId":{$ne: endorser._id}}
          ]
        }
      }
    },
    {
      "$push": { "skills.$[outer].endorsers": endorserData }
    },
    {
      "arrayFilters": [
        { "outer.skillId": ObjectId(req.params.skillId) }
      ]
    }

But this is not working, and along update, I need the updated result. 但这不起作用,并且随着更新,我需要更新的结果。

You can use addToSet function of mongoose arrays to keep their elements unique. 您可以使用猫鼬数组的addToSet函数保持其元素唯一。 https://mongoosejs.com/docs/api.html#mongoosearray_MongooseArray-addToSet https://mongoosejs.com/docs/api.html#mongoosearray_MongooseArray-addToSet

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

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