Andrew Horn
Andrew Horn

Reputation: 2549

How do I res.send within a promise in node.js?

I'm creating a little link shortener app. This the Express.js POST function. I want to send a document with the new url and the current number of documents in the database. This is mainly to make sure each website is associated with a unique, short number.

app.post('/api/shorturl/new', (req, res) => {
  var body = _.pick(req.body, ['url']);         // url attached to body.url with lodash

  Link.find({}).exec((err, res) => {            // Link is a mongoose model
    var count = res.length;
    var newSite = new Link({ website: body.url, count });
    newSite.save((err) => {
      if (err) console.log(err);
    })
    res.send(newSite);
  });
});

When the program gets to res.send(newSite), the console says that res.send is not a function. It's because it's within the promise, but I'm not really sure how to get it out and keep the code functional. How can I get the response to send?

Thanks!

Upvotes: 1

Views: 1675

Answers (2)

Phillip Thomas
Phillip Thomas

Reputation: 1469

It is likely your Link function is overriding expressjs's res. Try renaming res variable in Link.find({}).exec((err, res) => { to allow the res.send(newSite); to use the res variable from the scope above it.

Upvotes: 1

dhilt
dhilt

Reputation: 20744

It is not that res that you need. It's overrided by inner callback argument. You need to rename inner res into _res for example:

app.post('/api/shorturl/new', (req, res) => {
  var body = _.pick(req.body, ['url']);         // url attached to body.url with lodash

  Link.find({}).exec((err, _res) => {            // Link is a mongoose model
    var count = _res.length;
    var newSite = new Link({ website: body.url, count });
    newSite.save((err) => {
      if (err) console.log(err);
    })
    res.send(newSite);
  });
});

Upvotes: 4

Related Questions