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?

8/5/2013 8:02:10 PM

Accepted Answer

Mongoose Models inherit from Documents, which have a toObject() method. I believe what you're looking for should be the result of doc.toObject().

8/24/2015 3:13:02 PM

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';

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow