Mongoose:在查询中调用对象方法 select

Mongoose: call object method in query select

我有一个架构,并向其中添加了一个方法:

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

我有机会做到吗?

它不适用于 method, but it will with a 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
});