Reputation: 392
By default MongoDB on collection.save() returns a WriteResult object as stated in the documentation:
The save() returns a WriteResult object that contains the status of the insert or update operation.
But with Mongoose (and I guess the underlying mongodb driver in node) you can add a second parameter that is populated with the entire object that you just inserted and with the new _id:
var user = new User(req.body);
user.save(function (err, userResult) {
if (err) {
log.error(err);
}
log.debug('User data: ', userResult);
});
So my question:
Does userResult
contain retrieved data from Mongo and it's a fresh object OR is the object passed already passed into the save() method and from the database call is merged with only some partial data like the generated _id and/or created date?
Upvotes: 2
Views: 329
Reputation: 1158
To answer your question, the object returned is a new object -- not the original one (so user
!= userResult
)
Mongoose supports a few options -- new: true
and lean: false
settings may be of interest to you to modify how data is returned in different operations (if you want it to be a new option or do not care).
You can verify this 'new object' is the case by using the following:
var user = new User(req.body);
user.save(function (err, userResult) {
if (err) {
log.error(err);
}
user.name = 'TEST';
console.log(`${userResult.name} will be undefined but ${user.name} will not be`);
log.debug('User data: ', userResult);
});
Upvotes: 0
Reputation: 8141
If you take a look at Model.prototype.save()
:
https://github.com/Automattic/mongoose/blob/8cb0e35/lib/model.js#L254
It looks like you get back the same model instance (self
) in your userResult
.
Upvotes: 1