使用Mongoose时出现“对象没有xxx方法”的错误

6
我正在尝试使用Mongoose将MongoDB与Node.js连接起来。以下是我的代码。当我尝试通过api/users进行GET/POST时,我会收到错误提示。
TypeError: Object function model(doc, fields, skipId) {
[08/14 21:28:06 GMT+0800]     if (!(this instanceof model))
[08/14 21:28:06 GMT+0800]       return new model(doc, fields, skipId);
[08/14 21:28:06 GMT+0800]     Model.call(this, doc, fields, skipId);
[08/14 21:28:06 GMT+0800]   } has no method 'list'

请问有人能解释一下我做错了什么吗?我不得不将我的代码分成不同的文件,因为我有很多函数,我不想把它们弄乱在app.js或index/routes.js中。

app.js

//database connection 
mongoose.connect('....');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
 console.log("Conncection Success !");
});

users_module= require('./custom_modules/users.js');

users_module.init_users();
...
    app.get('/api/users',user.list);  // routing code from expressjs 

/custom_modules/users.js

function init_users() {

    userSchema = mongoose.Schema({
        //id: Number,
        usernamename: String,
        hash: String,
        ...

    });

    userSchema.methods.list = list;

    UserModel = mongoose.model('User', userSchema);

}

function list() {
    return UserModel.find(function (err, users) {
        if (!err) {
            return users;
        } else {
            return console.log(err);

        }
    });
});

exports.init_users = init_users;

routes/user.js

exports.list = function (req, res){

    var users = UserModel.list();  // <---------- This is the error Line 
    return res.send(users);

}

你在哪一行看到那个错误? - zs2020
我更新了问题上的错误,并指出了错误发生的行。错误发生在routes/user.js内部。 - geeky_monster
UserModel 没有 list 方法。你可以通过使用 methods. 将其添加到 UserModel 的实例中。你可以使用 UserModel.list = list 来添加它。 - WiredPrairie
如果我执行 userSchema.list = list,这样做有帮助吗? - geeky_monster
嗨@WiredPrairie,请将其作为答案放置,我会接受它。你是正确的。它起作用了。 - geeky_monster
1个回答

5
在Mongoose中,model对象的methods属性用于向模型对象的实例添加函数。因此,在您的代码中,函数list被添加到UserModel的实例中。如果您想要一个像静态函数一样的单例函数,那么可以直接将其添加到调用mongoose.model('UserModel', userModelSchema);返回的UserModel对象中:
UserModel.list = list;

现在,你可以调用它来返回所有用户的列表。
请注意,它仍然是一个异步函数。因此,你不能只返回调用函数的结果,因为通常情况下它会是空的。`find` 是异步的,所以你的 `list` 函数还需要接受一个回调函数,在列表返回时可以被调用:
UserModel.list(function(list) {
   res.render(list);
});

你的最后一段话让我更加清楚了。谢谢!我现在明白了。 - geeky_monster
1
静态方法也可以使用关键字 statics 来定义 - animalSchema.statics.findByName = function (name, cb){ } - geeky_monster

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接