下划线克隆Mongoose对象和删除属性不起作用?

JP *_*son 8 javascript clone mongoose node.js underscore.js

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

例:

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

以前没有用.

但是,如果我这样做:

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

我不明白为什么delete使用Underscore 调用克隆对象不起作用,但是如果我使用hacky JSON.string/JSON.parse,它可以工作.

有关这种行为的任何想法?

Rya*_*arn 6

我只是碰到了类似的问题来试图取代_id使用id.这样做对我有用:

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

也许它会开始,如果你更换工作delete ui["_id"]delete ui._id或使用toObject替代_.clone.