I have added a transform function to my Schema's toObject to strip certain properties, and change the name of _id to id. It works great when I use findOne and call toObject on the result, but I also have a find({}, (err, items) => {...}) command. There's no way to call toObject on the array.
Here's my schema:
var ItemSchema = new Schema({
version: {type: String, default: '1.0.0'},
created: {type: Date, default: Date.now},
modified: {type: Date, default: Date.now},
properties: Schema.Types.Mixed
}, {
toObject: {
transform: (doc, ret) => {
// remove the _id and __v of every document before returning the result
ret.id = doc.id;
delete ret._id;
delete ret.__v;
}
}
});
I've looked it up, and could only find this question, where the recommended answer is to use lean() - which does not help me.
As a workaround, I added the line var result = items.map(x => x.toObject());, and while it works great, I wonder if there's a way to trigger the transform automatically on any document returned - single or array, so I won't have to iterate over the results.
toObjectmanually if you have added the correct options to the schema. could you provide code for how you added the transformation totoObject? I suspect the key is there