FANDOM



While I do hope this gets patched at some point, presently you CANNOT get the identity of the new record as far as I can tell. The one place where that piece of information is emitted just craps it out into the ether and never passes it back to anywhere useful.

However if you MODIFY Mongoose's model class you can retrieve this precious bit of information. In the internal function "complete inside the "save" method of model.js if you use this version:

 function complete (err, docs) {
    if (err) return promise.error(err);
    promise.complete(docs[0]);
    self.emit('save', docs[0]);
  };

Then the saved document (in raw JSON, not activeRecord) will be returned as the second parameter of the callback.

I.e., this now WORKS:

var robot = new mongoose.model('Robot');
robot.name = 'Darth Vader'; // he's more machine than man
robot.save(function(err, new_robot) {
  if (err) throw err;
  console.log("Darth Vader's ID: " + new_robot._id);

});

If you note the examples in Mongoose never have a second parameter for the save callback - which makes sense - they simply assume that the fact THAT you have saved a document is all that's important, not the new record's KEY.

Its worth noting that models are emitters and that the following also works nicely:

var robot = new mongoose.model('Robot');
robot.name = 'Darth Vader'; // he's more machine than man
robot.save();
robot.on('save', function(new_robot) {
  if (err) throw err;
  console.log("Darth Vader's ID: " + new_robot._id);
});

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.