node.js 如何将 Mongoose 文档转换为普通对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7503450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:36:00  来源:igfitidea点击:

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

node.jsmongoose

提问by respectTheCode

I have a document from a mongoose find that I want to extend before JSON encoding and sending out as a response. If I try adding properties to the doc it is ignored. The properties don't appear in Object.getOwnPropertyNames(doc)making a normal extend not possible. The strange thing is that JSON.parse(JSON.encode(doc))works and returns an object with all of the correct properties. Is there a better way to do this?

我有一个来自猫鼬的文档,我想在 JSON 编码和作为响应发送之前扩展它。如果我尝试向文档添加属性,它会被忽略。这些属性不会出现在Object.getOwnPropertyNames(doc)使正常扩展不可能的情况下。奇怪的是,它JSON.parse(JSON.encode(doc))可以工作并返回一个具有所有正确属性的对象。有一个更好的方法吗?

回答by jmar777

Mongoose Models inherit from Documents, which have a toObject()method. I believe what you're looking for should be the result of doc.toObject().

Mongoose Models 继承自Documents,它有一个toObject()方法。我相信你正在寻找的应该是doc.toObject().

http://mongoosejs.com/docs/api.html#document_Document-toObject

http://mongoosejs.com/docs/api.html#document_Document-toObject

回答by JohnnyHK

Another way to do this is to tell Mongoose that all you need is a plain JavaScript version of the returned doc by using lean()in the query chain. That way Mongoose skips the step of creating the full model instance and you directly get a docyou can modify:

另一种方法是通过lean()在查询链中使用,告诉 Mongoose 您需要的只是返回文档的纯 JavaScript 版本。这样 Mongoose 就跳过了创建完整模型实例的步骤,你直接得到一个doc可以修改的:

MyModel.findOne().lean().exec(function(err, doc) {
    doc.addedProperty = 'foobar';
    res.json(doc);
});

回答by alban maillere

the fast way if the property is not in the model :

如果属性不在模型中,快速方法:

document.set( key,value, { strict: false });

document.set( key,value, { strict: false });

回答by Jalasem

A better way of tackling an issue like this is using doc.toObject()like this

解决这样的问题的一个更好的办法是使用doc.toObject()这样的

doc.toObject({ getters: true })

other options include:

其他选项包括:

  • getters:apply all getters (path and virtual getters)
  • virtuals:apply virtual getters (can override getters option)
  • minimize:remove empty objects (defaults to true)
  • transform:a transform function to apply to the resulting document before returning
  • depopulate:depopulate any populated paths, replacing them with their original refs (defaults to false)
  • versionKey:whether to include the version key (defaults to true)
  • getters:应用所有吸气剂(路径和虚拟吸气剂)
  • virtuals:应用虚拟吸气剂(可以覆盖吸气剂选项)
  • minimize:删除空对象(默认为 true)
  • transform:在返回之前应用于结果文档的转换函数
  • depopulate:删除任何填充的路径,用它们的原始引用替换它们(默认为 false)
  • versionKey:是否包含版本密钥(默认为 true)

so for example you can say

所以例如你可以说

Model.findOne().exec((err, doc) => {
   if (!err) {
      doc.toObject({ getters: true })
      console.log('doc _id:', doc._id)
   }
})

and now it will work.

现在它会起作用了。

For reference, see: http://mongoosejs.com/docs/api.html#document_Document-toObject

参考:http: //mongoosejs.com/docs/api.html#document_Document-toObject

回答by dd619

To get plain object from Mongoose document, I used _docproperty as follows

为了从 Mongoose 文档中获取普通对象,我使用_doc了如下属性

mongooseDoc._doc  //returns plain json object

I tried with toObjectbut it gave me functions,arguments and all other things which i don't need.

我试过了,toObject但它给了我函数、参数和所有其他我不需要的东西。

回答by kaushik_pm

You can also stringify the object and then again parse to make the normal object. For example like:-

您还可以将对象字符串化,然后再次解析以生成普通对象。例如像:-

const obj = JSON.parse(JSON.stringify(mongoObj))

回答by Antonio Brandao

A convenient way is to apply it straight to the model schema.

一种方便的方法是将其直接应用于模型模式。

As stated in the Mongoose documentation:

正如猫鼬文档中所述:

"To apply these options to every document of your schema by default, set your schemas toObject option to the same argument."

“要将这些选项默认应用于架构的每个文档,请将架构 toObject 选项设置为相同的参数。”

schema.set('toObject', { virtuals: true })

schema.set('toObject', { virtuals: true })