首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在一个路由中NodeJS两个查询

在一个路由中NodeJS两个查询
EN

Stack Overflow用户
提问于 2017-12-17 00:03:52
回答 3查看 81关注 0票数 1

我需要在同一渲染文件(show.hbs)中显示InvitationComments

我在这里有这段代码,它工作得很好,除了我不能实现注释也会显示。我真的很感谢任何人的帮助。

我没有在这段代码中得到任何错误。

代码语言:javascript
运行
复制
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);
});
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-12-17 00:17:46

你可以这样做,

代码语言:javascript
运行
复制
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();
});

并使用邀请和评论来呈现它

票数 1
EN

Stack Overflow用户

发布于 2017-12-17 01:52:52

Tnx到@vibhor1997a,但这个更漂亮

代码语言:javascript
运行
复制
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();
}
票数 1
EN

Stack Overflow用户

发布于 2017-12-17 00:16:51

您没有粘贴错误消息,但我非常确定它类似于Error: Can't set headers after they are sent to the client

只需嵌套您的查询或使用await https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47847507

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档