Shadid
Shadid

Reputation: 4252

How to pass an express.js response object to another module

I am trying to pass an Express response object to a different module I have. So in my server.js file I have this:

const room = require('../controller/rooms_controller')
app.post('/rooms',  function(req, res){
    var name = req.body.roomname
    var loc  = req.body.loc
    room.newRoom(name, loc,  res)
}) 

I am trying to pass the res object to the rooms_controller module. Now my rooms_controller module looks like this:

const Room  = require('../models/room')

exports.newRoom = function(name, loc, res){


    Room.findOne({'location': loc}, function(err, room, res){
        if(err){
            res.send({err: err})
        }
        if(room){
            res.send({room: room})
        }else{
            var newRoom = new Room()
            newRoom.location = loc
            newRoom.name     = name
            newRoom.save(function(error){
                if(err){
                    res.send({ error: error })
                }
                res.send({room: newRoom})
            })
        }
    })



}

So in my database the records are getting created but I am getting the cannot read property send of undefined error in my terminal.

Upvotes: 0

Views: 1763

Answers (1)

Froast
Froast

Reputation: 901

You are doing it correctly but are overwriting res because you redefine it on this line

Room.findOne({'location': loc}, function(err, room, res){

So res is the response from Room.findOne instead of the argument to newRoom which is your actual response object. Use a different variable name for one of them.

Upvotes: 3

Related Questions