0

a quick one:

Why is Mongoose change/upgrading the _id field of a document when I push an update? Is this an intended behavior?

Thanks.

This is the update I use inside my PUT route, and it returns successfully the updated model, but unfortunately with a new _id for doc

Document.findById(req.params.doc_id, function (err, doc) {
    if (err)
        res.send(err)

    // Do some subdoc stuff here …

    doc.save(function (err) {
        if (!err) {
            console.log('Success!');
            res.json(doc);
        } else {
            console.log(err);
        }

    });
});

2 Answers2

1

Okay, problem solved: I was logging the wrong _id (doh!)

1

Mongoose docs http://mongoosejs.com/docs/2.7.x/docs/model-definition.html suggest using update or findOne

ex:

var query = { name: 'borne' };
Document.update({"_id": req.params.doc_id}, { name: 'jason borne' }, {}, function(err, numAffected){
  if (!err) {
    console.log('Success!');
    res.json(numAffected);
  } else {
    console.log(err);
  }
});

or

Model.findOne({ "_id": req.params.doc_id }, function (err, doc){
  doc.name = 'jason borne';
  doc.save();
  // here you could use your save instead, but try not to use the doc again
  // it is confusing
  // doc.save(function (err, documentSaved, numberAffected) {
  //   if (!err) {
  //     console.log('Success!');
  //     res.json(documentSaved);
  //   } else {
  //     console.log(err);
  //   }
  // });
});

Later I also found the findById update suggested in some docs http://mongoosejs.com/docs/documents.html, which seems to be up to date, check the version you are using and also double check the two times you are using doc in your functions here. Also you can check your mongoDB and see if there are more than one record getting saved.

db.documents.find( {} )
earlonrails
  • 4,966
  • 3
  • 32
  • 47
  • Hi. Well, 2.7 is outdate and I use 3.8.* of Mongoose. As for save and update, it really depends: I mostly use Mongoose middleware (pre/post) on save to hash a password interim. This post describes that nicely: http://stackoverflow.com/questions/22278761/mongoose-difference-between-save-and-using-update –  Dec 11 '14 at 08:42