When returning Mongoose documents from a MongoDB database, you can't just edit the returned document. You either need to convert it to a plain JavaScript object by the .toObject()
function - which has yet to work for me - or JSON.parse(JSON.stringify(doc))
it.
My question is why is this the case? Why aren't they just returned as plain, simple, easy to use JavaScript objects by default?
To turn a Mongoose document into a plain object, we can use the lean method. MyModel. findOne(). lean().
The _doc property is where Mongoose stores the "raw" value of the document. A document itself has getters/setters, the $__ property, etc.
Because Mongoose documents have additional functionality, like various built-in and custom instance methods. It allows you to call document.save(...)
after changing a document, for instance.
If you want your queries to return plain objects, you can also use the lean
option.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With