Node.Js Express和Mongoose响应模型修改

我对Node.js的开发很陌生。 还callback仍然相当bedazzle我,虽然我有一些asynchronousfunction的经验。

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

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

这是我目前如何让所有用户在数据库中,但这也返回密码和其他敏感信息。 我想知道最有效的方法来“转换”这个数据到同一个对象没有一些属性或改变属性,如添加一个“fullName”由firstName + lastName;

所以当返回所有的用户,我想有这样的东西

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

不知道“convertToOtherModel”function可以放在某个地方,以便它可以在用户…但任何想法如何做到这一点将有所帮助!

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

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

您也可以使用aggregation framework并通过合并不同字段的值来创build新字段

 User.aggregate([ {$project: { username: '$username', fullName: {$concat: ['$firstName', ' ', '$lastName']} }} ], function(error, users) { console.log(users) }) 
 personSchema .virtual('fullName') .get(function () { return this.name.first + ' ' + this.name.last; }) .set(function (v) { this.name.first = v.substr(0, v.indexOf(' ')); this.name.last = v.substr(v.indexOf(' ') + 1); }) 
  1. 对于像FullName这样的东西,你可以创buildvirtual模式。

    链接在这里: http : //mongoosejs.com/docs/guide.html

  2. 你将不得不select你想输出的列,我不确定你是否可以专门黑名单列(所有列减去密码列)

你可以这样做,只返回一些属性:

 function filterUser(user) { let { property1, property2 } = user; return { property1, property2 }; } res.json( users.map(filterUser) ); 

或者使用lodash更便携的方式:

 res.json( users.map(user => _.pick(user, ['prop1', 'prop2'])); 

请参阅: https : //lodash.com/docs/4.17.4#pick

要使用lodash版本,您首先需要添加:

 const _ = require('lodash'); 

到你的代码,并运行在你的项目的目录中:

 npm install lodash --save 

覆盖您的用户架构的toJSON方法。

 UserSchema.methods.toJSON = function () { var user = this; // Modify your document object here return { fullName: user.firstName + " " + user.lastName } // Pick other fields too if you want // _.pick(user, ["otherField"]); }; 

然后像他们那样发送 –

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