6

I use the following update command to model:

Room.update({_id: roomId, status: 'live'}, {$push: {"users" : {_id: user._id, loginName: user.loginName}}}, {}, function(err, room) {

model:

{
    _id: "56c0d9e332f6ddc80ec7271c",
    name: "Reqqqq2",
    creator: "MegaDaddgy",
    status: "live",
    __v: 0,
    users: [
        {
        _id: "56c0a986eeb118741109a45f",
        loginName: "MegaDaddgy"
        },
        {
        _id: "56bf96f56a0c220812f055e6",
        loginName: "Maad"
        }
    ]
}

I don't want to add duplicate fields to users, How can I do this?

1
  • 1
    Presumably you are following the convention of _id being "unique" so: Room.update({ "_id": roomId, "status": "live", "users._id": { "$ne": user._id } }, { "$push": { "users": { "_id": user._id, "loginName": user.name } } }). So basically looking for where the users _id is not present ( $ne is not equal to ). Not to hard is it now. Commented Feb 14, 2016 at 23:40

1 Answer 1

9

The $addToSet could prevent the duplicate entry present in the users

Room.update(
   {_id: roomId, status: 'live'}, 
   {$addToSet: 
      {"users" : {_id: user._id, loginName: user.loginName}}}, function(err, room) {

Another way could be done through $ne same as Blakes mentioned in the comment as below

Room.update({ "_id": roomId, "status": "live", "users._id": { "$ne": user._id } }, { "$push": { "users": { "_id": user._id, "loginName": user.name } } })
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.