Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js Mongoose:在查询选择中调用对象方法_Node.js_Mongodb_Mongoose - Fatal编程技术网

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
});