2015-02-09 25 views
0

我有一個模式,並添加到它的方法:貓鼬:在查詢調用對象方法選擇

// 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' 

我想在動物的查詢和獲取方法結果選擇:

Animal.find({type: 'dog'}).select('type name slug'); // [{type: 'dog', name: 'Bill', slug: 'dog-Bill'}] 

我可以這樣做嗎?

回答

2

它不會與method一起使用,但它將與virtual屬性一起使用。

var animalSchema = new Schema({ name: String, type: String }); 

animalSchema.virtual('slug').get(function() { 
    return this.type + '-' + this.name; 
}); 

爲了具有虛擬性當模型的converted to JSON,你需要通過virtuals: true

animal.toJSON({ virtuals: true }) 

您可以將您的模式配置爲始終解析虛擬。

var animalSchema = new Schema({ 
    name: String, 
    type: String 
}, { 
    toJSON: { 
     virtuals: true 
    } 
}); 

或者

animalSchema.set('toJSON', { 
    virtuals: true 
});