MongoDB not saving data

I'm making an app with express and mongoose, https://github.com/findjashua/express_app

  • app.coffee

    app.post '/user', user.add
    
  • models/user.coffee

    createUser = (req) ->
        user = new User
            name : req.body.name
            email : req.body.email
            phone : req.body.phone
        return user
    
    # ...
    
    exports.add = (req, res) ->
        user = createUser req
        res.send dbService.save(user)
    
  • services/db.coffee

    exports.save = (document)->
        document.save (err)->
            if err
                console.log err
            return document
    

When I make a post request to add a new user, it doesn't save anything and I can't think of any reason why. Any ideas?

document.save() is asynchronous, so return isn't really an option within dbService.save().

  • The res.send() will have already finished before return document is evaluated.
  • It also returns document to the code that called the callback, which is within document.save, not to your code within user.coffee.

You'll need to adjust dbService.save() to accept a callback so you can res.send() the finished document:

exports.save = (document, callback) ->
    document.save (err, document) ->
        if (err)
            callback(err)
        else
            callback(null, document)
exports.add = (req, res) ->
    user = createUser req
    dbService.save user, (err, user) ->
        res.send err ? user

Note: that 1st snippet can be simplified, depending on whether or not .save() needs to do anything else:

exports.save = (document, callback) ->
    document.save callback