I would like to use lean option as for save.
The callback of save returns also a mongoose document and not a JS object which I want to change using a lean-like call.
Using lean for queries and toObject in saves' callback functions seems like a confusion to me.
Any ideas?
If you don't want to use lean, then your best bet is to form a new object from the returned Mongoose object
Person.findOne({
_id: req.user.id
}, function(err, result) {
if (err)
return next(err);
return (200, {
id: result._id,
spouse: result.spouse,
children: result.children
});
});
Maybe my post was not clear, sorry.
I would like to use the lean but on saving operations as well.
The callbacks of the save functions like "save" or "update" return with schema object and I cannot use lean to have a pure JS object.
This is my problem. I would like to use lean for save and update as well.
@imrefazekas, Save, Update, Create, and Remove are not "queries", so they don't take the .lean()
directive as is.
You could use the .toObject()
method on the returned object to get it without the schema:
p.save(function (err, returned) {
var leanObject = returned.toObject(); // has many options: http://mongoosejs.com/docs/api.html#document_Document-toObject
assert.equal(leanObject.schema, null);
});
hummity hums...save()
should have a lean option?
How would you imagine save() and lean working together? AFAIK that doesn't make sense.
ummm, it's a been a few days but currently it's like so
user.save(function(err,user){
//user is full-fledged etc
});
with lean option, it would/could be
user.save({
lean:true
},function(err,user){
//user is *not* full-fledged etc
});
isn't that right?
@ORESoftware nope, because the 2nd parameter in the callback to save is the exact same document. Mongoose doesn't ask the database for the newly updated doc. For instance,
user.save(function(err, _user){
user === _user; // true
});
oh ok got it :) my bad
for the record, the solution provided above by @refack still work like a charm in 2017
@peterpeterparker I disagree and think this is still an issue for users who want data to be returned from all database operations instead of Mongoose instances.
@alex-dixon I was just pointing out that the solution of @refack for the save
operation is still valid and functional in 2017, nothing more, nothing less ;)
@peterpeterparker You're right. Sorry. Shouldn't have directed that toward you.
@alex-dixon no worries
should we use lean()
with Model.create()
?
Never because you can't use lean()
with Model.create()
:p
got it :)
Most helpful comment
@imrefazekas, Save, Update, Create, and Remove are not "queries", so they don't take the
.lean()
directive as is.You could use the
.toObject()
method on the returned object to get it without the schema: