我有3个mongoose Collection :董事会,线和回复.每个回复属于1个线程,每个线程属于1个Board. 当我想要向Thread添加一个新的回复时,我会使用表单数据发出POST请求,其中包括thodid(来自现有的Thread).

当我向现有的线程id发出POST请求时,这段代码运行得很好,但是当我试图用一个不可用的线程id发出POST请求时,控制台显示了很多东西,我不知道错误是什么.(预期输出:"找不到线程").

请帮帮我.我是个新手,真的很想收到大家的意见!

我的问题是在/api/replies/:board号公路.如果没有updateThread,控制台不会像我预期的那样显示"Thread Not Found",而是一个像error这样的长对象(我滚动到顶部,但似乎控制台没有足够的空间来显示完整的错误)

'use strict';

const BoardModel = require('../models').Board;
const ThreadModel = require('../models').Thread;
const ReplyModel = require('../models').Reply;

module.exports = function (app) {
  
  app.route('/api/threads/:board').post(async (req, res) => {
    const { text, delete_password } = req.body;
    let { board } = req.body;
    if (!board) {
      board = req.params.board;
    }
    
    //Add new Thread
    const newThread = new ThreadModel({
      text: text,
      reported: false,
      delete_password: delete_password,
      replies: [],
    })
    let saveThread = await newThread.save();
    console.log("New thread added:");
    console.log(newThread.text);

    //Add new Board
    const oldBoard = await BoardModel.findOne({ name: board }).exec();
    if (!oldBoard) {
      const newBoard = new BoardModel({
        name: board,
        threads: [newThread],
      })
      let saveBoard = await newBoard.save();
      console.log("New thread added to this new board:");
      console.log(newBoard.name);
      res.json(saveBoard)
    } else {
      oldBoard.threads.push(newThread);
      let saveBoard = await oldBoard.save()
      console.log("New thread added to the existing board:");
      console.log(oldBoard.name);
      res.json(saveBoard);
    }
  });
    
  app.route('/api/replies/:board').post(async (req, res) => {
    const { text, delete_password, thread_id } = req.body;
    let { board } = req.body;
    if (!board) {
      board = req.params.board;
    }
   
    const updateThread = await ThreadModel.findById(thread_id).exec();
    if (!updateThread) {
      console.log("Thread not found");   
      res.send("Thread not found");
    }
    //Add new Reply
    const newReply = new ReplyModel({
      text: text,
      delete_password: delete_password,
      reported: false,
    })
    let saveReply = await newReply.save();
    console.log("New reply added:");
    console.log(newReply.text);

    //Update Thread
    updateThread.replies.push(saveReply);
    let saveThread = await updateThread.save();
    console.log('New reply added to this thread:');
    console.log(updateThread.text);

    res.json(saveReply);
  });

};

推荐答案

通过将exec()链接到您的Model方法上,它提供了更完整的堆栈跟踪,这就是为什么您会得到长错误消息的原因.我认为可能对您有帮助的是使用try/catch块来捕获错误,如果有错误,然后决定如何处理它,或者使用早期的Return语句返回响应.如下所示更新代码:

try{ //< Use of try/catch
   const updateThread = await ThreadModel.findById(thread_id);
    if (!updateThread) {
      console.log("Thread not found");   
      return res.send("Thread not found"); //< Early return
    }
    //Add new Reply
    const newReply = new ReplyModel({
      text: text,
      delete_password: delete_password,
      reported: false,
    })
    let saveReply = await newReply.save();
    console.log("New reply added:");
    console.log(newReply.text); //< Did you mean saveReply.text here?

    //Update Thread
    updateThread.replies.push(saveReply);
    let saveThread = await updateThread.save();
    console.log('New reply added to this thread:');
    console.log(updateThread.text); //< Did you mean saveThread.text here?


    res.json(saveReply);
}catch(err){
   console.log(err);
   res.status(500).json({
      message: 'An error occurred on the server'
   });
}


Node.js相关问答推荐

Azure虚拟机上的JS Express:可疑请求?

错误:找不到模块';/var/apps/前端/bash';

使用参考中断Mongoose模型-Node.js

FiRestore UPDATE方法引发错误:&Quot;错误:13内部:收到代码为1&Quot;的RST_STREAM

填充函数在Node.js和MongoDB中不起作用

当变量在另一个文件中初始化时,在初始化错误之前无法访问变量

如何发送比特币BTC使用发送加密使用WIF密钥在 node ,js

如何修复我的 NodeJS SSE 写入函数以在后续调用中更新 HTML?

未授权使用联合身份未授权用户角色从 Amplify graphQL 访问类型 Y 上的 X

Prisma,只有一个用户的行可以有真值,@@unique(userId, isActive)

我应该转译我的 TypeScript 应用程序吗?

try 在 NodeJS 项目中实现 SimplePay (OTP) 支付网关,但我无法获得与技术文档中相同的签名

访问 Mongoose 查询之外的变量

获取数组的至少一个元素包含子字符串的文档

如何使用 UglifyJS 缩小文件夹中的多个 Javascript 文件?

将 myproject/.npmrc 与注册表一起使用

带有加密的nodejs中的SALT和HASH密码

如何使用 Node.js 将 base64 编码图像(字符串)直接上传到 Google Cloud Storage 存储桶?

要求('babel/register')不起作用

CORS 错误:预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段授权