0

In my task collection, I have a users field. While updating, I need to check if the same userid is in users.assigned, I need to leave or if a different userid is assigned, I need to push that record.

db.tasks.find({
"_id" : ObjectId("60ddd690c6d9014f7a8c9af2")
"createdDate" : ISODate("2021-07-01T14:50:51Z"),
"modifiedDate" : ISODate("2021-07-01T14:50:51Z"),
"users" : {
        "assigned" : [
            {"userid" : ObjectId("5d9fd8613d598088d2ea5e2b"),
                "team" : "APPLICATIONS DEVELOPMENT"},           
        ],
})

I need to push if this userid is not on my list.

{"userid" : ObjectId("5de8ad4263d21b900e1be386"),
  "team" : "APPLICATIONS DEVELOPMENT"},

My output should be like

"users" : {
        "assigned" : [
            {"userid" : ObjectId("5d9fd8613d598088d2ea5e2b"),
                "team" : "APPLICATIONS DEVELOPMENT"},
            {"userid" : ObjectId("5de8ad4263d21b900e1be386"),
                "team" : "APPLICATIONS DEVELOPMENT"},
        ],
}

I tried using findByIdAndUpdate, I don't know how exactly I should form

1 Answer 1

2
  • check not equal to condition for userid
  • $push element in assigned array
await YourSchemaModel.findByIdAndUpdate(
  {
    "users.assigned.userid": {
      $ne: ObjectId("5de8ad4263d21b900e1be386")
    }
  },
  {
    $push: {
      "users.assigned": {
        "userid": ObjectId("5de8ad4263d21b900e1be386"),
        "team": "APPLICATIONS DEVELOPMENT"
      }
    }
  }
)

Playground

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.