Underscore's Cloning of Mongoose Objects and Deleting Properties Not Working?

半腔热情 提交于 2019-12-06 22:29:08

问题


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?


回答1:


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.




回答2:


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;
};


来源:https://stackoverflow.com/questions/9418967/underscores-cloning-of-mongoose-objects-and-deleting-properties-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!