Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are Mongoose documents not plain JavaScript objects by default?

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?

like image 378
Aron Avatar asked Jun 01 '16 09:06

Aron


People also ask

How do you turn a mongoose document into a plain object?

To turn a Mongoose document into a plain object, we can use the lean method. MyModel. findOne(). lean().

What is _DOC mongoose?

The _doc property is where Mongoose stores the "raw" value of the document. A document itself has getters/setters, the $__ property, etc.


1 Answers

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.

like image 143
robertklep Avatar answered Sep 27 '22 19:09

robertklep