简体   繁体   中英

Mongoose : filter then update document if it exists , otherwise create it

In the following method , i'm trying to search for a document using an email adress i provide. If the document exists i want to update the _id field, otherwise i create a totally new document .

function (accessToken, refreshToken, profile, done) {

    var newUser = new User();

    newUser.name = profile.displayName;
    newUser.email = profile.emails[0].value.toString();

    options = { upsert: true, new: true, setDefaultsOnInsert: true };
    update = { '_id': newUser._id };

    User.findOneAndUpdate({ 'email': profile.emails[0].value.toString() }, update, options, function (err, user) {
        newUser.save(function (err) {
            if (err)
                throw err;
            newUser.token = newUser.generateJwt();
        });
    });
    return done(null, newUser);
}

i get the following error in the console :

events.js:183 throw er; // Unhandled 'error' event ^ BulkWriteError: E11000 duplicate key error index: databasename.users.$ id dup key

Thank you for your help !

You can try this using upsert : true . This will create the document if not found

  User.findOneAndUpdate(query, update, options, function(error, result) {
   if (error) return;

    // do something with the document
  });

ps. You don't need to do newUser.save(..) . That'll do that for you if not found. But I don't know why are you trying to update the id as this would cause fatal consequences

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM