Underline cloning of Mongoose objects and deleting properties not working?

I am using Mongoose and I want to remove the _id property from my Mongoose instance before sending a 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 one did not work.

However, if I do this:

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

I do not understand why calling delete for a cloned object using Underscore does not work, but if I execute the hacker JSON.string / JSON.parse, it works.

Any thoughts on this behavior?

+8
javascript clone mongoose
source share
2 answers

I just ran into a similar problem trying to replace _id with id . 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 work if you replace delete ui["_id"] with delete ui._id or use toObject instead of _.clone .

+6
source share

To add to the previous answer, there is another way to achieve the same. The toObject function applies the transformation to the document, which is determined by the schema.options.toObject.transform function, for example

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

All Articles