如何从MongoDB + Node.js + Mongoose获取修改后的json输出

编程入门 行业动态 更新时间:2024-10-23 21:31:06
本文介绍了如何从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的字段名称? _id到IdentityNo?

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输出

本文发布于:2023-11-22 19:17:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618677.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Node   MongoDB   js   json   Mongoose

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!