I am running the Express.js application and I have the following setup:
models.js
var schemaOptions = { toJSON: { virtuals: true }, toObject: { virtuals: true } }; var modelSchema = new mongoose.Schema({ name : { type: String, required: true } }, schemaOptions); modelSchema.virtual('id').get(function() { return this._id; });
controllers.js
exports.getModel = function(req, res) { Model.find().select('name').exec(function(err,model) { if (err) { return res.status(500).json({errors:err, message: 'Internal server error'}); } return res.status(200).json({model: model}); }); };
The result of the above query will look something like this:
{ "_id":"dakjdjkakda", "name":"MontyPython", "id":"dakjdjkakda" }
due to the Virtual attribute that I defined in modelSchema.
If I changed the query select statement to:
Model.find().select('-_id name').exec(function(err,model) {}
Result:
{"name":"MontyPython", "id":null }
I believe this is because the Virtual attribute points to the _id attribute.
My question is how to remove the _id attribute in the request, but keep the id alias I created?
source share