Consider I have a Mongoose schema defined
var Schema_MySchema = new mongoose.Schema({
Field1: String, Field2: String
});
I have added virtual attribute & setting options in the following way:
Schema_MySchema.virtual('USERNAME').get(function () {
return this.Field1;
});
Schema_MySchema.set('toJSON', { virtuals: true });
Using the schema object to retrieve the data from MongoDB as follows:
var Mod_Obj = mongoose.model('SchemaName', Schema_MySchema);
var Model_Instance = new Mod_Obj();
Model_Instance.find({}, function (err, docs) {
/*
Here I get a object docs with following structure:
[{ _id: ObjectId("511XXXdff9c4c419000008"),
Field1: 'SOMEvalueFromMongoDB_1',
Field2: 'SOMEvalueFromMongoDB_2',
USERNAME: 'SOMEvalueFromMongoDB_1'
}]
*/
});
Now I want to remove actual attribute returned from MongoDB, say I want to remove Field1
from docs
I tried following ways to remove:
1. delete docs.Field1;
2. var Json_Obj = docs.toJSON(); delete Json_Obj.Field1;
3. var Json_Obj = docs.toObject({ virtuals: true }); delete Json_Obj.Field1;
4. delete docs[0].Field1;
5. delete docs[0]['Field1'];
All the ways didn't work. :-(
If execute for testing on simple JSON it worked:
var a = { 'A' : 1, 'B': 2 };
delete a.A;
console.log(a); //prints only object with B attribute only. i.e. { B: 2 }
Could anyone tell me whats wrong here?
Thanks in Advance...