我正在运行一个可以通过 Mongoose 访问的 MongoDB 来存储用户记录。我在服务器上也有下划线。我有一个 RESTful API,其路由从数据库返回一个集合(对象数组)。我想将完整的集合返回给客户端但是从每个对象中删除密码元素,这样就不会发送给客户端。在任何人说什么之前,我将在最终版本中使用 bcrypt 对密码进行加盐和散列处理:)
今天我在数据库中只有一个条目,用于用户“administrator”。这是我的 route 的代码:
app.get('/users', function(req, res) {
User.find().sort({'userName': 'ascending'}).exec(function(err, data) {
_.each(data, function (element, index, list) {
console.log('userName=' + element.userName);
console.log('password=' + element.password);
delete element.password;
console.log('keys: ' + _.keys(element));
console.log('password=' + element.password);
console.log(_.omit(element, 'password'));
});
res.json(data);
});
});
我返回给浏览器的是:
[{"_id":"54058e6eb53dd60730295f59","modifiedOn":"2014-09-01T15:19:10.012Z",
"userName":"administrator","password":"stackoverflow","role":"administrator",
"__v":0,"createdBy":"54058e6eb53dd60730295f59","createdOn":"2014-09-01T15:19:10.004Z",
"previousLogins":[],"accountIsLocked":false,"loginAttempts":0}]
这很好,因为 res.json(data)
语句只是将原始 data
发送回浏览器 - 这不是问题所在。问题是 delete
(如果我使用 .omit
)似乎对我的收藏不起作用!如您所见,有很多用于调试的 console.log
,这是输出的内容:
userName=administrator
password=stackoverflow
keys: $__,isNew,errors,_maxListeners,_doc,_pres,_posts,save,_events
password=stackoverflow
{ _id: 54058e6eb53dd60730295f59,
modifiedOn: Mon Sep 01 2014 19:19:10 GMT+0400 (GST),
userName: 'administrator',
password: 'stackoverflow',
role: 'administrator',
__v: 0,
createdBy: 54058e6eb53dd60730295f59,
createdOn: Mon Sep 01 2014 19:19:10 GMT+0400 (GST),
previousLogins: [],
accountIsLocked: false,
loginAttempts: 0 }
_.keys
的输出显示了我在 console.log(element)
时看不到的键(我假设来自对象原型(prototype)?)但没有可通过 element.key
访问的键。
知道为什么我会看到这种行为吗?
最佳答案
问题是 data
传递给 exec
回调函数实际上是一个 Document
对象——它可以被认为是 模型
由 Mongoose 创建。这些对象有很多有用的方法,它们会记住与 db 等的连接 - 但您将无法将它们作为普通对象进行处理。
解决方案是指示 Mongoose 您实际上需要纯 JS 对象作为使用 lean()
查询的结果:
User.find().sort({'userName': 'ascending'}).lean().exec(function(err, data) {
// process the data
});
或者,您应该能够使用 .toObject()
方法将每个模型转换为普通对象,然后对其进行过滤:
var filtered = _.map(data, function(model) {
return _.omit(model.toObject(), 'password');
});
res.json(filtered);
...但我宁愿使用第一种方法。 )
关于javascript - underscore.js .keys 和 .omit 没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25767334/