【问题标题】:Underscore's Cloning of Mongoose Objects and Deleting Properties Not Working?Underscore 克隆 Mongoose 对象和删除属性不起作用?
【发布时间】:2012-03-14 04:59:00
【问题描述】:

我正在使用 Mongoose,我想在向客户端发送 JSON 响应之前从我的 Mongoose 实例中删除 _id 属性。

例子:

var ui = _.clone(userInvite);
delete ui["_id"];
console.log(JSON.stringify(ui)); //still has "_id" property, why?

以前的不行。

但是,如果我这样做:

var ui = JSON.parse(JSON.stringify(userInvite)); //poor man's clone
delete ui["_id"];
console.log(JSON.stringify(ui)); //"_id" is gone! it works!

我不明白为什么在使用下划线的克隆对象上调用delete 不起作用,但如果我执行 hacky JSON.string/JSON.parse,它会起作用。

对这种行为有什么想法吗?

【问题讨论】:

  • 可能 mongoose 正在诱骗您并将 _id 实现为 getter/setter 而不是属性。试试Object.getOwnPropertyDescriptor(userInvite, "_id").get
  • 修改克隆猫鼬对象的任何属性也是不可能的。

标签: javascript node.js clone mongoose underscore.js


【解决方案1】:

我刚刚遇到了一个类似的问题,试图用id 替换_id。这样做对我有用:

Schema.methods.toJSON = function(options) {
  var document = this.toObject(options);
  document.id = document._id.toHexString();
  delete(document._id);
  return document;
};

如果您将delete ui["_id"] 替换为delete ui._id 或使用toObject 而不是_.clone,它可能会开始工作。

【讨论】:

  • 我刚刚在尝试从我的用户对象中删除密码时遇到了这个问题,并且对于为什么“删除 user.password”不起作用。在它上面使用 toObject() 似乎已经成功了。我的猜测是 mongoose 实际上并没有将属性存储为对象的属性,而是使用 toString 方法或类似方法动态构建它。
【解决方案2】:

只是补充上一个答案,还有另一种方法可以实现相同的目标。 'toObject' 函数将转换应用于由 schema.options.toObject.transform 函数定义的文档,例如

schema.options.toObject.transform = function(doc, ret) {
    ret.id = doc._id;
    delete ret._id;
};

【讨论】:

  • 不幸的是,这似乎导致TypeError: Cannot set property 'transform' of undefined
猜你喜欢
  • 2016-08-05
  • 2016-12-12
  • 2017-04-26
  • 2016-01-19
  • 2015-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多