Reputation: 686
In my Group model, I'm exporting one function that pass the result of a query using a callback.
In my router file, I'm calling this function, after properly requiring the other file.
That's my ./models/groups.js
:
var groupSchema = new mongoose.Schema({
[...]
module.exports.getAll = function(cb) {
groupSchema.find({}, function(err, groups) {
if (err) return cb(err)
cb(null, groups)
})
}
[...]
module.exports = mongoose.model('Group', groupSchema);
and that's my ./routes/groups.js
file.
var Group = require('../models/group')
router.route('/groups')
.get(function(req, res, next) {
Group.getAll( function(err, group){
if (err) res.send(err)
res.send(group)
})
})
[...]
This is not working, because every time I make a get request, I'm getting a TypeError: undefined is not a function
error. I know I can make the query right on my router file, but I think separating things between routes and methods would be a better practice.
Upvotes: 0
Views: 1233
Reputation: 46323
You're overwriting the object where you defined the getAll
function when you assign a new value to module.exports
.
You've got 2 options:
Extend the model with the getAll
function, and export as you do today.
This basically looks like:
var model = mongoose.model('Group', groupSchema);
model.getAll = function(cb) {
...
};
module.exports = model;
But that's not very "clean".
Export the model under a named property alongside the getAll
function.
This basically looks like this:
module.exports.getAll = function(cb) {
...
};
module.exports.model = mongoose.model('Group', groupSchema);
Then in your routes, you'd have:
var Groups = require('../models/group');
// Now you have Groups.getAll & Groups.model
This is more flexible overall and will allow you to export other types/functions/values as you see fit.
Upvotes: 1