Mongoose:查询选择中的调用对象方法

时间:2015-02-09 12:09:55

标签: 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.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'}]

我有机会这样做吗?

1 个答案:

答案 0 :(得分: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
});