node.js 如何获取 json 对象数组而不是 mongoose 文档

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12210870/
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 16:14:44  来源:igfitidea点击:

How to get array of json objects rather than mongoose documents

node.jsmongodbexpressmongoose

提问by Erik

When I do find operation like the follows:

当我找到如下操作时:

Collection.find({name: 'Erik'}, function (err, docs) {
   // do momething
});

'docs' variable is populated with an array of fully functional mongoose documents. But I need to get an array of pure JSON objects.

'docs' 变量填充了一组功能齐全的猫鼬文档。但我需要获取一组纯 JSON 对象。

I know I can loop through the 'docs' array by forEach and get an objects by using .toJSON() method. Does mongoose support the feature I'm interested?

我知道我可以通过 forEach 遍历“docs”数组并使用 .toJSON() 方法获取对象。猫鼬是否支持我感兴趣的功能?

回答by JohnnyHK

If you're using Mongoose 3.x you can use the leanquery option to do this:

如果您使用的是 Mongoose 3.x,您可以使用lean查询选项来执行此操作:

Collection.find({name: 'Erik'}).lean().exec(function (err, docs) {
    // docs are plain javascript objects instead of model instances
});

回答by Uday Hiwarale

.exec(function(err, docs){
    docs= docs.map(o => o.toObject());

This will include virtualsand getters

这将包括虚拟吸气剂