Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose array push without duplicate

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?

like image 998
Jackson Avatar asked Mar 13 '23 07:03

Jackson


1 Answers

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 } } })
like image 96
zangw Avatar answered Mar 25 '23 11:03

zangw