简体   繁体   English

为什么Mongoose文档默认不是普通的JavaScript对象?

[英]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. 从MongoDB数据库返回Mongoose文档时,您不能只编辑返回的文档。 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. 你需要通过.toObject()函数将它转换为普通的JavaScript对象 - .toObject()没有对我JSON.parse(JSON.stringify(doc)) - 或者JSON.parse(JSON.stringify(doc))它。

My question is why is this the case? 我的问题是为什么会这样? Why aren't they just returned as plain, simple, easy to use JavaScript objects by default? 为什么它们不是默认返回简单,易用的JavaScript对象?

Because Mongoose documents have additional functionality, like various built-in and custom instance methods . 因为Mongoose文档具有其他功能,例如各种内置和自定义实例方法 It allows you to call document.save(...) after changing a document, for instance. 例如,它允许您在更改文档后调用document.save(...)

If you want your queries to return plain objects, you can also use the lean option. 如果希望查询返回普通对象,也可以使用lean选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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