"Object has no xxx method" error when using Mongoose

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(); // <---------- This is the error Line return res.send(users); } 
+6
source share
1 answer

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

 UserModel.list = list; 

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

Note that this is still an asynchronous function. Thus, you cannot simply return the results of a function call, since it will be empty. find is asynchronous, so your list function should also accept a callback that can be called when the list has been returned:

 UserModel.list(function(list) { res.render(list); }); 
+5
source

Source: https://habr.com/ru/post/951722/


All Articles