我正在运行Express.js应用程序,我有以下设置:
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});
- });
- };
上述查询的结果如下:
- { "_id":"dakjdjkakda","name":"MontyPython","id":"dakjdjkakda" }
因为我在modelSchema中定义了Virtual属性.
如果我将查询select语句更改为:
- Model.find().select('-_id name').exec(function(err,model) {}
结果将是:
- {"name":"MontyPython","id":null }