MongoDB : How to insert an embedded document in an array if a certain field is unique else update it

落爺英雄遲暮 提交于 2019-12-20 06:25:29

问题


I am trying to insert an embedded document if a certain field is unique else update it in mongoDB.

Here is what I have so far:

User.findOneAndUpdate(
        {
            _id : <idOfTheUserSavingTheContact>,
            //'arrayOfContacts.email' : <email of the contact>
        },
        {
            $addToset: { 
                arrayOfEmailsOfUnregisteredUsersWatchedByThisUser: {
                    firstName : req.body.firstName,
                    lastName : req.body.lastName,
                    email : req.body.email,
                }
            }
        },
        { new: true, upsert:true, runValidators: true},
        function (err, updatedUser) {
            if(err){
                return err;
            }else {
                console.log(updatedUser)
            }
        }
    );

My model looks like so:

const UserSchema = new mongoose.Schema({
  username: {
    type: String,
  },
  contacts: [{
      firstName: {
        type: String,
      },
      lastName: {
        type: String,
      },
      email: {
        type: String,
        required: true,
      }
    }], 
});

I would like to: insert a contact if the email is unique else add one if no embedded contact document exists with the same email.

The results I am having with my current setup is that the 'same' document will be added but with a different _id.

I am aware that you can do this in multiple db commands but I would like to do it in just one command(if possible and if efficient). Thank you.

来源:https://stackoverflow.com/questions/57670212/mongodb-how-to-insert-an-embedded-document-in-an-array-if-a-certain-field-is-u

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!