0

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.

2
  • Have you loaded the router module in your groups js file? Commented Jul 15, 2015 at 9:52
  • 1
    You re probably overriding getAll function when you export the entire groupSchema. Try exporting getAll function after groupSchema export Commented Jul 15, 2015 at 9:54

1 Answer 1

1

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:

  1. 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".

  2. 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.