Underscore 克隆 Mongoose 对象并删除属性不起作用?

发布于 2025-01-08 18:19:23 字数 561 浏览 1 评论 0原文

我正在使用 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,它就会起作用。

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

I'm using Mongoose and I want to remove the _id property from my Mongoose instance before I send the JSON response to the client.

Example:

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

The previous didn't work.

However, if I do:

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

I don't understand why calling delete on a cloned object using Underscore doesn't work, but if I do the hacky JSON.string/JSON.parse, it works.

Any thoughts on this behavior?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

晨曦慕雪 2025-01-15 18:19:23

我刚刚遇到类似的问题,试图用 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

I just came across a similar issue trying to replace _id with id. Doing this worked for me:

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

Maybe it will start working if you replace delete ui["_id"] with delete ui._id or use toObject instead of _.clone.

所谓喜欢 2025-01-15 18:19:23

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

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

Just to add to the previous answer, there is one more way to achieve the same. 'toObject' function applies transformation to the document which is defined by the schema.options.toObject.transform function, e.g

schema.options.toObject.transform = function(doc, ret) {
    ret.id = doc._id;
    delete ret._id;
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文