Underscore 克隆 Mongoose 对象并删除属性不起作用?
我正在使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我刚刚遇到类似的问题,试图用
id
替换_id
。这样做对我有用:如果您将
delete ui["_id"]
替换为delete ui._id
或使用toObject
,也许它会开始工作而不是_.clone
。I just came across a similar issue trying to replace
_id
withid
. Doing this worked for me:Maybe it will start working if you replace
delete ui["_id"]
withdelete ui._id
or usetoObject
instead of_.clone
.只是为了补充之前的答案,还有一种方法可以实现相同的目的。 'toObject' 函数将转换应用于由 schema.options.toObject.transform 函数定义的文档,例如
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