如何从MongoDB + Node.js + Mongoose获取修改后的json输出 [英] How to get modified json output from MongoDB + Node.js + Mongoose

查看:364
本文介绍了如何从MongoDB + Node.js + Mongoose获取修改后的json输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑将我的收藏存储在 MongoDB 中,如下所示:

Consider my collection is store as follows in MongoDB:

  { 
    _id: 'Unique_Value',
    FieldMONGO1: 'ngfn',
    FieldMONGO2: { SomeKey: ['val1','val2','val...']  },
  }

当我在Mongoose的Model Instance上使用find方法进行检索时.我得到以下 JSON输出:

When I retrieve using find method on Model Instance of Mongoose. I get the following JSON output:

  { 
    _id: 'Unique_Value',
    FieldMONGO1: 'NAME_value',
    FieldMONGO2: { SomeKey: ['val1','val2','val...']  },
  }

两者完全相同.

问题:有什么办法可以将FieldMONGO1更改为FirstName,将FieldMONGO2更改为NewName的字段名称? _idIdentityNo?

Question: Is there any way so that I can change the field names like FieldMONGO1 to FirstName, FieldMONGO2 to NewName & _id to IdentityNo?

这样我的输出将是这样的:

So that my output will be something like this:

  { 
    IdentityNo: 'Unique_Value',
    FirstName: 'ngfn',
    NewName: { SomeKey: []  },
  }

了解解决方案::按原样获取JSON输出,然后更改Node.js代码中的字段(属性)名称.但是这里的问题是,它变成了阻塞代码.如果请求大量数据,这会增加服务器的开销.

Know Solution: Is to get the JSON output as is and then change field (attribute) name in Node.js code. But here the problem is, it becomes a blocking code. Which can create overhead on server if huge data is requested.

有人可以帮我找出一些有效的方法吗?

Could anyone help me out in find out some efficient way of doing the same?

提前谢谢

推荐答案

Virtuals >猫鼬.

check out Virtuals in mongoose.

在参考链接中查看示例.

check out the example in the reference link.

如果您喜欢进行调整

urSchema.virtual('FirstName').get(function () {
  return this.FieldMONGO1;
});

您可以做到.

在SO上检查此答案.

这篇关于如何从MongoDB + Node.js + Mongoose获取修改后的json输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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