问题
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