Node.Js Express和猫鼬响应模型修改 [英] Node.Js Express and Mongoose Response Model Modify

查看:85
本文介绍了Node.Js Express和猫鼬响应模型修改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Node.js开发很陌生.尽管我对异步函数有一定的经验,但回调仍然使我大为震惊.

I'm quite new to Node.js development. Also callbacks still quite bedazzle me although I have some experience with async functions.

我正在使用猫鼬的.find()函数在数据库中的用户"集合中进行搜索.问题是我也想显示这些用户,但是我不想显示数据库中所有可用的属性.

I'm using mongoose's .find() function to search in a Users collection in the DB. The problem is I also want to display these users but I wouldn't want to display all the properties availible in the Database.

...
function(req,res){
    User.find(function(err,users){
        res.json(users);
    }) 
}
...

这是我目前在数据库中获取所有用户的方式,但这还会返回密码和其他敏感信息.我想知道将这些数据转换"为同一个对象的最有效方法,而无需某些属性或更改属性,例如添加一个由firstName + lastName组成的"fullName";

This is how I'm currently getting all my users in the DB, but this also return passwords and other sensitive information. I would like to know the most effiecient way to "convert" this data into the same object without some properties or with altered properties like adding a "fullName" comprised of firstName + lastName;

因此,在返回所有用户时,我希望拥有

So when returning all the users I would like to have something like

...
function(req,res){
    User.find(function(err,users){
        res.json(users.convertToOtherModel());
    }) 
}
...

不确定"convertToOtherModel"功能是否可以放在用户可以使用的地方...但是任何有关此操作的想法都将有所帮助!

Not sure the "convertToOtherModel" function can be placed somewhere so that it works on users... but any idea on how to do this would help!

推荐答案

您可以将第二个参数传递给find()并指定要返回或不想返回的字段,而不用查询返回所有字段

Instead of making query to return all fields you can pass second argument to find() and specify which fields you want or don't want to return

User.find({}, {password: 0}, function(error, users) {
  console.log(users)
})

您还可以使用 aggregation framework 并通过隐藏不同的值来创建新字段字段

You can also use aggregation framework and create new field by concating values of different fields

User.aggregate([
    {$project: {
        username: '$username',
        fullName: {$concat: ['$firstName', ' ', '$lastName']}
    }}
    ], function(error, users) {
        console.log(users)
    })

这篇关于Node.Js Express和猫鼬响应模型修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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