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);
}
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With