I am trying to use Mongoose to connect MongoDB with Nodejs.
I have my code as shown below. When I try to get / post through api / users, I get
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 explain what I'm doing wrong? I had to split my code into different files, because I have many functions, and I do not want to mess them up either in 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();