Mongoose - 将方法添加到回调中返回的对象
Mongoose - add method to object that is returned in the callback
有没有办法给回调返回的对象添加函数?
User.find({'age':'20'}, function(err, users){
users.function();
});
似乎statics
只适用于模型。示意图:
User.static();
和methods
仅适用于实例
(new User()).method();
None 其中似乎对用户有效,我认为这只是一个普通的 js 对象变量。我错过了什么吗?
Schema.method
描述,来自文档:
Adds an instance method to documents constructed from Models compiled from this schema.
所以,如果你这样做:
var userSchema = new Schema({
username: String,
age: Number
});
userSchema.method('showAge', function () {
return this.age;
});
,并在查询返回的文档中调用您的方法,例如:
User.findOne({'age':'20'}, function(err, user){
console.log(user.showAge());
});
应该可以。也许您遇到问题是因为您在 array
中调用方法 users.function()
。记住:find
方法 returns 文档数组。
有没有办法给回调返回的对象添加函数?
User.find({'age':'20'}, function(err, users){
users.function();
});
似乎statics
只适用于模型。示意图:
User.static();
和methods
仅适用于实例
(new User()).method();
None 其中似乎对用户有效,我认为这只是一个普通的 js 对象变量。我错过了什么吗?
Schema.method
描述,来自文档:
Adds an instance method to documents constructed from Models compiled from this schema.
所以,如果你这样做:
var userSchema = new Schema({
username: String,
age: Number
});
userSchema.method('showAge', function () {
return this.age;
});
,并在查询返回的文档中调用您的方法,例如:
User.findOne({'age':'20'}, function(err, user){
console.log(user.showAge());
});
应该可以。也许您遇到问题是因为您在 array
中调用方法 users.function()
。记住:find
方法 returns 文档数组。