1

This is my User Collection

{ _id: ObjectId("589803bf53860d4a3475afa3"),
  "username": "fadeltd",
  "gender": "Male",
  "updatedAt": ISODate("2017-02-06T05:03:59.969Z"),
  "createdAt": ISODate("2017-02-06T05:03:59.969Z"),
  "shoppingList": [{
      "title": "Personal List",
      "ingredients": ["5 Eggs"]
  }]
})

What I'm trying to do is to push data to my shopping list, with $addToSet so that there will be no duplicate shopping list data

This is my script

User.update({ 
        _id: ObjectId("589803bf53860d4a3475afa3"), 
        'shoppingList.title': "Personal List"
    }, 
    {
        $addToSet: {
            "shoppingList.$.ingredients": ["5 Eggs", "3 Milks"]
        }
    })

But when I try that script I get this

{ _id: ObjectId("589803bf53860d4a3475afa3"),
  "username": "fadeltd",
  "gender": "Male",
  "updatedAt": ISODate("2017-02-06T05:03:59.969Z"),
  "createdAt": ISODate("2017-02-06T05:03:59.969Z"),
  "shoppingList": [{
      "title": "Personal List",
      "ingredients": ["5 Eggs", ["5 Eggs", "3 Milks"]],
  }]
})

I want the ingredients to be ["5 Eggs", "3 Milks"] instead of nested array ["5 Eggs", ["5 Eggs", "3 Milks"]]

1 Answer 1

1

Use the $each modifier which allows you to add multiple values to an array

User.update(
    { 
        "_id": ObjectId("589803bf53860d4a3475afa3"), 
        "shoppingList.title": "Personal List"
    }, 
    {
        "$addToSet": {
            "shoppingList.$.ingredients": { 
                "$each": ["5 Eggs", "3 Milks"] 
            }
        }
    }
)
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.