0

I want to do is update a record and insert it if it doesn't exist with mongoose. Here is my code:

module.exports.upsertUser = function(user) {
    var options = {userName : 'Ricardo'}
    Users.findOneAndUpdate({email: user.email}, options, {upsert:true}).exec();
}

And:

var promise = Users.upsertUser(user);
promise
.then(function(results){
    ...
}
.catch(function(err){
    ...
}

When I execute the promise, each time a new user is created with the same email.

I'm not sure if I'm performing the update incorrectly. I've tried it in the same way but with update and it does not work either.

Can you help me? Thanks!

Ricardo
  • 7
  • 2

2 Answers2

0

according to your coding what findOneAndUpdate() does is that it finds this document/user's document that you are looking for to edit which in this case what you are using to search for this user's document that you want to edit it's document is with his email. Now your second argument modifies that part of the document that you wanted to modify, but this option has to be attached with some mongodb operators (pay a visit to this link for a list of them: https://docs.mongodb.com/manual/reference/operator/update/) but in your case what you need is the $set operator.so i would modify your code like this:

module.exports.upsertUser = function(user) { var options = Users.findOneAndUpdate({email: user.email}, {$set:{ userName : 'Ricardo' }}, { returnOriginal: true}).exec(); };

so try the above modification let's see how it works

MR EXCEL
  • 41
  • 3
0

You need to put the return without the exec:

module.exports.upsertUser = function(user) {
    var options = {userName : 'Ricardo'}
    return Users.findOneAndUpdate({email: user.email}, options, {upsert:true, new: true});
}


var promise = Users.upsertUser(user);
promise.then(function(results){
   if(results) {
      console.log(results);
   } else {
      console.log('!results');
   }
}.catch(function(err){
    ...
}

FYI: The default is to return the unaltered document. If you want the new, updated document to be returned you have to pass an additional argument: {new:true} with the upsert option.

fernandezbcn
  • 151
  • 4