in group model, i'm exporting 1 function pass result of query using callback.
in router file, i'm calling function, after requiring other file.
that's ./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 ./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 not working, because every time make request, i'm getting typeerror: undefined not function error. know can make query right on router file, think separating things between routes , methods better practice.
you're overwriting object defined getall function when assign new value module.exports.
you've got 2 options:
extend model
getallfunction, , export today.
looks like:var model = mongoose.model('group', groupschema); model.getall = function(cb) { ... }; module.exports = model;but that's not "clean".
export model under named property alongside
getallfunction.
looks this:module.exports.getall = function(cb) { ... }; module.exports.model = mongoose.model('group', groupschema);then in routes, you'd have:
var groups = require('../models/group'); // have groups.getall & groups.modelthis more flexible overall , allow export other types/functions/values see fit.
Comments
Post a Comment