4

I'm currently working on an app using Express + Node. I recently added a new .post route to the app.js file, using the following syntax:

app.post('/api/posts/saveComment', posts.saveComment);

posts is defined above as:

var posts = require('./routes/posts.js');

And saveComment is defined as so:

exports.saveComment = function(req, res) {
    //function stuff in here, yada yada
}

Now, node is throwing an error when I try to run the app:

Error: .post() requires a callback functions but got a [object Undefined]

saveComment is clearly a function, I'm not understanding why it can't see this. I have another function defined right above saveComment that I'm able to reference completely fine without error, however copying that functions contents to that of saveComment still yields the same error. I'm at a loss, any help is much appreciated.

Per request, contents of posts.js

var mongo = require('../mongo.js');

exports.queryAll = function(req, res) {
    var db = mongo.db;

    db.collection('posts', function(err, collection) {
        collection.find().toArray(function(err, doc) {
            if (err)
                res.send({error:err})
            else
                res.send(doc)

            res.end();
        });
    });
}

exports.saveCommment = function(req, res) {
    var db      = mongo.db,
        BSON    = mongo.BSON,
        name    = req.body.name,
        comment = req.body.comment,
        id      = req.body.id;

    db.collection('posts', function(err, collection) {
        collection.update({_id:new BSON.ObjectID(id)}, { $push: { comments: { poster:name, comment:comment }}}, function(err, result) {
            if (err) {
                console.log("ERROR: " + err);
                res.send(err);
            }
            res.send({success:"success"});
            res.end();
        });
    });
}
tymeJV
  • 103,943
  • 14
  • 161
  • 157

3 Answers3

10

Well...embarrassing answer, saveCommment is defined with 3 m's in my posts.js. Ugh.

tymeJV
  • 103,943
  • 14
  • 161
  • 157
0

Have you looked at other related questions?

Such as:

Understanding callbacks in Javascript and node.js

understanding the concept of javascript callbacks with node.js, especially in loops

I've battled with this topic myself and have to say that callbacks are fundamental for a happy node.js app.

Hope this helps.

Community
  • 1
  • 1
fancyguts
  • 41
  • 3
0

I write my exports the following way. maybe this will help you :)

  module.export = {
     savecomment : function(){
         yada yada
      },
     nextfunction : function(){
     }
   }

Using the functions:

 var helper = require('helper.js')

 helper.savecomment();
jansmolders86
  • 5,449
  • 8
  • 37
  • 51