问题描述
我正在使用Mongoose,我想在将JSON响应发送到客户端之前从我的Mongoose实例中删除 _id
属性。
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.
示例:
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!
我不明白为什么要调用删除
在使用Underscore的克隆对象上不起作用,但如果我使用hacky JSON.string / JSON.parse,它可以工作。
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?
推荐答案
我刚遇到试图用 id
替换 _id
的类似问题。这样做对我有用:
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;
};
如果你替换 delete ui [_ id],它可能会开始工作
使用删除ui._id
或使用 toObject
而不是 _ .clone
。
Maybe it will start working if you replace delete ui["_id"]
with delete ui._id
or use toObject
instead of _.clone
.
这篇关于下划线克隆Mongoose对象和删除属性不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!