Node.js Mongoose:在查询选择中调用对象方法
我有一个模式,并向其中添加了一个方法:Node.js Mongoose:在查询选择中调用对象方法,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我有一个模式,并向其中添加了一个方法: // define a schema var animalSchema = new Schema({ name: String, type: String }); // assign a function to the "methods" object of our animalSchema animalSchema.methods.slug = function () { return type: this.type + '-' + this.n
// define a schema
var animalSchema = new Schema({ name: String, type: String });
// assign a function to the "methods" object of our animalSchema
animalSchema.methods.slug = function () {
return type: this.type + '-' + this.name;
}
这样使用:
var Animal = mongoose.model('Animal', animalSchema);
var dog = new Animal({ type: 'dog', name: 'Bill });
dog.slug(); // 'dog-Bill'
我想在select中查询动物并获取方法结果:
Animal.find({type: 'dog'}).select('type name slug'); // [{type: 'dog', name: 'Bill', slug: 'dog-Bill'}]
有没有可能我可以这样做?它不适用于,但适用于属性
var animalSchema = new Schema({ name: String, type: String });
animalSchema.virtual('slug').get(function () {
return this.type + '-' + this.name;
});
为了在模型运行时拥有虚拟属性,您需要传递virtuals:true
animal.toJSON({ virtuals: true })
您可以将模式配置为始终解析虚拟
var animalSchema = new Schema({
name: String,
type: String
}, {
toJSON: {
virtuals: true
}
});
或
animalSchema.set('toJSON', {
virtuals: true
});