使用模型模式中的方法访问 Mongoose 模型
Access Mongoose Model with method from Model's Schema
我想知道这个 Mongoose 模型场景是否可行,但我目前无法对其进行测试。
var xSchema = new mongoose.Schema({
Data: String
});
xSchema.methods.getData = function(ID){
SSS.findById(ID, function(err, found){
if(err) throw err;
return found;
}
}
SSS = mongoose.model('x', xSchema);
SSS.getData()
returnData
可以吗?
这是我的测试代码,请确保mongoose.model
的第一个参数应该与SSS
相同,就像我的代码如下所示。
var xSchema = new mongoose.Schema({
Data: String
});
xSchema.methods.getData = function(ID, callback){
SSS.findById(ID, function(err, found){
if(err) throw err;
else
callback && callback(found);
});
}
var SSS = mongoose.model('SSS', xSchema);
function findX() {
var s1 = new SSS({data: 'dd'});
// the `"56d7c1b29741d2982750c725"` is the `_id` of `{Data: 'test'}`
s1.getData("56d7c1b29741d2982750c725", function(d) {
console.log(d);
})
}
function saveX() {
var s = new SSS({Data: 'test'});
s.save(function (err) {
if (err)
console.log(err);
else
console.log('save sss successfully');
});
}
xSchema.methods
定义 instance method
,也许 Statics
方法更适合您的情况
xSchema.statics.getData = function (ID, cb) {
那么你可以通过
访问这个方法
SSS.getData(ID, cb)
我想知道这个 Mongoose 模型场景是否可行,但我目前无法对其进行测试。
var xSchema = new mongoose.Schema({
Data: String
});
xSchema.methods.getData = function(ID){
SSS.findById(ID, function(err, found){
if(err) throw err;
return found;
}
}
SSS = mongoose.model('x', xSchema);
SSS.getData()
returnData
可以吗?
这是我的测试代码,请确保mongoose.model
的第一个参数应该与SSS
相同,就像我的代码如下所示。
var xSchema = new mongoose.Schema({
Data: String
});
xSchema.methods.getData = function(ID, callback){
SSS.findById(ID, function(err, found){
if(err) throw err;
else
callback && callback(found);
});
}
var SSS = mongoose.model('SSS', xSchema);
function findX() {
var s1 = new SSS({data: 'dd'});
// the `"56d7c1b29741d2982750c725"` is the `_id` of `{Data: 'test'}`
s1.getData("56d7c1b29741d2982750c725", function(d) {
console.log(d);
})
}
function saveX() {
var s = new SSS({Data: 'test'});
s.save(function (err) {
if (err)
console.log(err);
else
console.log('save sss successfully');
});
}
xSchema.methods
定义 instance method
,也许 Statics
方法更适合您的情况
xSchema.statics.getData = function (ID, cb) {
那么你可以通过
访问这个方法SSS.getData(ID, cb)