简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM