Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error 'Object has no method xxx ' while using Mongoose

I am trying to use Mongoose for connecting MongoDB with Nodejs .

I have my code as below. When I am trying to do a GET/POST via api/users I get the

Error


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'

Can someone please explain what I am doing wrong ? I had to split my code into different files because I have a lot of functions and I dont want to mess them either my app.js or 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);

}
like image 800
geeky_monster Avatar asked Aug 14 '13 13:08

geeky_monster


1 Answers

The methods property of a model object in Mongoose is used to add functions to instances of model objects. So, in your code, the function list is added to an instance of UserModel. If you instead want to have a static like singleton function, then you could add it directly to the UserModel object returned by the call to mongoose.model('UserModel', userModelSchema);:

UserModel.list = list;

Now, you can call it to return the list of all users.

Note that it's still an asynchronous function though. So, you can't just return the results of calling the function, as it will be empty normally. find is async, so your list function also needs to accept a callback that can be called when the list has been returned:

UserModel.list(function(list) {
   res.render(list);
});
like image 152
WiredPrairie Avatar answered Sep 20 '22 13:09

WiredPrairie