Mongoose toObject和toJSON有什么区别? [英] What is the difference between Mongoose toObject and toJSON?

查看:588
本文介绍了Mongoose toObject和toJSON有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

toObject的Mongoose文档列出了功能,选项并提供了示例toObject的功能.

The Mongoose documentation for toObject lists features, options, and gives examples of functionality of toObject.

toJSON的Mongoose文档说这些选项与toObject相同,但是没有解释toJSON的作用. 文档说的其他地方

The Mongoose documentation for toJSON says the options are the same as toObject, but doesn't explain what toJSON does. Elsewhere the documentation says

toJSON与toObject选项完全相同,但仅适用 调用文档的toJSON方法时.

toJSON is exactly the same as the toObject option but only applies when the document's toJSON method is called.

toJSONtoObject的别名吗?如果没有,有什么区别?

Is toJSON an alias of toObject? If not, what are the differences?

推荐答案

看看

A look at the source code reveals that both methods call an internal $toObject method, but with toJSON passing a second, true parameter:

Document.prototype.toObject = function (options) {
  return this.$toObject(options);
};
...
Document.prototype.toJSON = function (options) {
  return this.$toObject(options, true);
};

第二个参数确定$toObject是使用toJSON还是toObject架构选项作为默认值.因此,除非这些架构选项的配置不同,否则这两种方法是相同的.

That second parameter determines whether $toObject uses the toJSON or toObject schema options for its defaults. So unless those schema options are configured differently, the two methods are identical.

这篇关于Mongoose toObject和toJSON有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆