简体   繁体   English

将 Mongoose 对象转换为特定的 json 模式(对象)

[英]Convert Mongoose object to particular json schema(object)

i have a requirement, when I am fetching data from MongoDB and using mongoose as an ORM.我有一个要求,当我从 MongoDB 获取数据并使用 mongoose 作为 ORM 时。 now the data that i fetch from DB, i keep in mongoose object.现在我从数据库中获取的数据,我保存在猫鼬对象中。 I do not want to send back all the information as response to client.我不想将所有信息作为对客户端的响应发回。 I have a specific JSON response schema template.我有一个特定的 JSON 响应架构模板。 i want to convert the mongoose object to this particular JSON object and then send the response.我想将猫鼬对象转换为这个特定的 JSON 对象,然后发送响应。

Pass in a filter to your .find() method that only retrieves the properties that you want.将过滤器传递给您的 .find() 方法,该方法仅检索您想要的属性。

collection.find({}).select('name age');

If you have large datasets, you can go the opposite route and exclude the fields you don't want如果您有大型数据集,您可以走相反的路线并排除您不想要的字段

collection.find({}).select('-created -createdBy');

http://mongoosejs.com/docs/queries.html http://mongoosejs.com/docs/queries.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM