How do you turn a Mongoose document into a plain object?
I have a document from a mongoose find that I want to extend before JSON encoding and sending out as a response. If I try adding properties to the doc it is ignored. The properties don't appear in Object.getOwnPropertyNames(doc)
making a normal extend not possible. The strange thing is that JSON.parse(JSON.encode(doc))
works and returns an object with all of the correct properties. Is there a better way to do this?
Mongoose Model
s inherit from Document
s, which have a toObject()
method. I believe what you're looking for should be the result of doc.toObject()
.
http://mongoosejs.com/docs/api.html#document_Document-toObject
Another way to do this is to tell Mongoose that all you need is a plain JavaScript version of the returned doc by using lean()
in the query chain. That way Mongoose skips the step of creating the full model instance and you directly get a doc
you can modify:
MyModel.findOne().lean().exec(function(err, doc) {
doc.addedProperty = 'foobar';
res.json(doc);
});
the fast way if the property is not in the model :
document.set( key,value, { strict: false });
JohnnyHK suggestion:
In some cases as @JohnnyHK suggested, you would want to get the Object as a Plain Javascript. as described in this Mongoose Documentation there is another alternative to query the data directly as object:
const docs = await Model.find().lean();
Conditionally return Plain Object:
In addition if someone might want to conditionally turn to an object,it is also possible as an option
argument, see find() docs at the third parameter:
const toObject = true;
const docs = await Model.find({},null,{lean:toObject});
its available on the functions: find()
, findOne()
, findById()
, findOneAndUpdate()
, and findByIdAndUpdate()
.
NOTE:
it is also worth mentioning that the _id
attribute isn't a string object as if you would do JSON.parse(JSON.stringify(object))
but a ObjectId from mongoose types, so when comparing it to strings cast it to string before: String(object._id) === otherStringId