underscore.js .keys和.omit没有按预期工作

时间:2014-09-10 13:55:33

标签: javascript object mongoose underscore.js

我正在通过Mongoose运行MongoDB以存储用户记录。我也在服务器上有下划线。我有一个RESTful API,其路由从数据库返回一个集合(对象数组)。我想将完整的集合返回给客户端,但从每个对象中删除密码元素,以便不会将其发送到客户端。在任何人说什么之前,我会使用bcrypt在最终版本中加密和散列密码:)

今天我在数据库中只有一个条目,用户'管理员'。这是我路线中的代码:

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)时看不到,但没有通过element.key可访问的键。

知道为什么我会看到这种行为吗?

1 个答案:

答案 0 :(得分:15)

问题是传递给data回调函数的exec实际上是一个Document对象 - 可以被认为是由Mongoose创建的Models的集合。这些对象有很多有用的方法,它们记得与db等的连接 - 但你不能将它们作为普通对象处理。

解决方案是通过lean()指示Mongoose您实际上想要普通的JS对象作为查询的结果:

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);

......但我宁愿使用第一种方法。 )