我正在运行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; });
Run Code Online (Sandbox Code Playgroud)
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});
});
};
Run Code Online (Sandbox Code Playgroud)
上述查询的结果如下:
{ "_id":"dakjdjkakda", "name":"MontyPython", "id":"dakjdjkakda" }
Run Code Online (Sandbox Code Playgroud)
因为我在modelSchema中定义了Virtual属性.
如果我将查询select语句更改为:
Model.find().select('-_id name').exec(function(err,model) {}
Run Code Online (Sandbox Code Playgroud)
结果将是:
{"name":"MontyPython", "id":null }
Run Code Online (Sandbox Code Playgroud)
我相信这是因为Virtual属性指向_id属性.
我的问题是,如何删除查询中的_id属性,但保留我创建的id别名?
如果你使用猫鼬,
您可以处理何时toJSON,您可以决定它的显示方式,但您不能在查询中提及它.
Model.find().select('name').exec(function(err,model) {}
new mongoose.Schema(yourSchema, {
toJSON: {
transform: function(doc, ret) {
ret.id = ret._id;
delete ret._id;
}
}
);}
Run Code Online (Sandbox Code Playgroud)
您可以使用全局方法。试试这个:
mongoose.plugin((schema) => {
schema.options.toJSON = {
virtuals: true,
versionKey: false,
transform(doc, ret) {
ret.id = ret._id;
delete ret._id;
}
};
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4656 次 |
| 最近记录: |