frenchbaguette
frenchbaguette

Reputation: 1339

NodeJS two queries in one route

I need to display Invitation and Comments in the same rendered file (show.hbs)

I have this code here, and it's working fine, except I cannot achieve that comment's would also display. I would really appreciate any help.

I'm not getting any errors with this code.

app.get('/invitation/:id', (req, res) => {

  let id = req.params.id;

  if(!ObjectID.isValid(id)){
    return res.status(404).send();
  }

  Comment.find({inviteId: id}).then((comment) => {
    if(!comment){
      return res.status(404).send();
    }
    res.render('show.hbs', {comment});
  }, (e) => {
    res.status(404).send();
  });

  Invitation.findById(id).then((invitation) => {
      if(!invitation){
        return res.status(404).send();
      }
    res.render('show.hbs', {invitation});
}, (e) => {
  res.status(404).send();
});

}, (e) => {
  console.log('Unable to find invitation', e);
});

Upvotes: 1

Views: 103

Answers (3)

Reza Ghorbani
Reza Ghorbani

Reputation: 2876

Tnx to @vibhor1997a but this is much prettier

try {
  let invitation = await Invitation.findById(id).then((invitation) => {
  if (!invitation) {
    return res.status(404).send();
  }
  let comments = await Comment.find({ inviteId: id })
  if (!comments) {
    return res.status(404).send();
  }
  return res.render('show.hbs', { comments, invitation});
} catch (e) {
  return res.status(500).send();
}

Upvotes: 1

vibhor1997a
vibhor1997a

Reputation: 2376

You can do something like this,

Invitation.findById(id).then((invitation) => {
if (!invitation) {
    return res.status(404).send();
}
Comment.find({ inviteId: id }).then((comment) => {
    if (!comment) {
        return res.status(404).send();
    }
    res.render('show.hbs', { comment, invitation});
}, (e) => {
    res.status(404).send();
});    
}, (e) => {
res.status(404).send();
});

and render it with both invitation and comment

Upvotes: 1

alfredopacino
alfredopacino

Reputation: 3241

You didn't paste your error message, but I'm pretty sure it's something like Error: Can't set headers after they are sent to the client.

Just nest your queries or use await https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await.

Upvotes: 0

Related Questions