我有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);
});
};