Ben Drury
Ben Drury

Reputation: 1376

Mongo DB Save tries to insert instead of update

I am doing a Mongo Schema.save(), which should automatically do an upsert, but it insists on trying to do an insert and then errors with

E11000 duplicate key error index

This is the Node function that does the save:

exports.ImpdateSave = function(req, res) {
    var theImpdate = new Impdate(req.body)
    if (theImpdate){
        var impdateId = req.params.id;
        console.log("Node API Impdate: ", theImpdate);
        console.log("Node API Impdate ID: ", impdateId);
        theImpdate.save(function(err) {
            if (err) {
                console.log(err);
                return res.send(400);
            }
            res.send(200);
        });
    } else {
        return res.status(400).send('There was no person data in the request to update. Please try again!');    
    }
};

Why is it unable to find the document when it does the initial search before the insert/update, but then finds it when it does the insert?

Output from Console:

Node API Impdate:  { _id: 5481c33cd8bf24f4235cff35,
  _creator: 54679200502e901427fec6de,
  name: 'XXXXX',
  address: 'XXXXXXXXXXXXXXXX',
  __v: 0}

Node API Impdate ID:  5481c33cd8bf24f4235cff35
{ [MongoError: insertDocument :: caused by :: 11000 E11000 duplicate key error index: fullstack-dev.impdates.$_id_  dup key: { : ObjectId('5481c33cd8bf24f4235cff35') }]
   name: 'MongoError',
   code: 11000,
   err: 'insertDocument :: caused by :: 11000 E11000 duplicate key error index: fullstack-dev.impdates.$_id_  dup key: { : ObjectId(\'5481c33cd8bf24f4235cff35\')
  }' }

Upvotes: 3

Views: 1549

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312045

Mongoose's save doesn't do an upsert like you're thinking. When you create a new Impdate object like you're doing here, it will always treat it as a new doc, even if the contained _id value already exists.

Instead, either findOne the doc by its _id, apply the new values from the body and save, or use findByIdAndUpdate.

Upvotes: 3

Related Questions