Issue with Anonymous message board project

Hi, I am currently going through the projects on the information security certification. I am currently stuck with a strange error. Right now, I am working on the post request to create a new board. The database is receiving the data in mongodb, but it is still saying I have an error on the localhost.

Screen Shot 2024-06-14 at 11.28.16 AM

Here is my api.js file:

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

module.exports = function (app) {
  
  app.route('/api/threads/:board').post((req, res) => {
    const { text, delete_password } = req.body;
    let board = req.body.board;
    if (!board) {
      board = req.params.board;
    }
    console.log("post", req.body);
    const newThread = new ThreadModel({
      text: text,
      delete_password: delete_password,
      replies: []
    });
    console.log("new thread", newThread);
    BoardModel.findOne({ name: board }).then(boardData => {
      if (!boardData) {
        const newBoard = new BoardModel({
          name: board,
          threads: []
        });
        console.log("new board", newBoard);
        newBoard.threads.push(newThread);
        newBoard.save().then((err, data) => {
          console.log("new board data", data);
          if (err || !data) {
            console.log(err);
            res.send("There was an error saving post.");
          } else {
            res.json(newThread);
          }
        });
      } else {
        boardData.threads.push(newThread);
        boardData.save().then((err, data) => {
          if (err || !data) {
            console.log(err);
            res.send("There was an error saving post.");
          } else {
            res.json(newThread);
          }
        });
      }
    });
  })
  app.route('/api/replies/:board');
}

In case this is necessary, here is my models.js file:

const mongoose = require('mongoose');
const { Schema } = mongoose;

const date = new Date();

const replySchema = new Schema({
    text: { type: String },
    delete_password: { type: String },
    reported: { type: Boolean, default: false },
    created_on: { type: Date, default: date },
    bumped_on: { type: Date, default: date },
    });
const threadSchema = new Schema({
    text: { type: String },
    delete_password: { type: String },
    reported: { type: Boolean, default: false },
    created_on: { type: Date, default: date },
    bumped_on: { type: Date, default: date },
    replies: { type: [replySchema]}
});
const boardSchema = new Schema({
    name: { type: String },
    threads: { type: [threadSchema] }
});

const Thread = mongoose.model("Thread", threadSchema);
const Reply = mongoose.model("Reply", replySchema);
const Board = mongoose.model("Board", boardSchema);

exports.Thread = Thread;
exports.Reply = Reply;
exports.Board = Board;

Hey, this error is coming from inside the if statement, in other words this may all be working. So were to begin here what is your expected output and the like, why are you thinking this is strange when its in the code and part of this API file?

 res.send("There was an error saving post.")

Hi, thanks for the reply. I know where the error is coming from, I just don’t understand why it is happening. The database is receiving the data, so the else statement should execute, but instead, the if statement is executing. That’s what is confusing me.

newBoard.save().then((err, data) =>

The callback to then on save does not give you an error and the data, just the returned document after the save promise resolves.

Mongoose v8.4.1: Documents

The save() method returns a promise. If save() succeeds, the promise resolves to the document that was saved.

doc.save().then(savedDoc => {
  savedDoc === doc; // true
});

So I would assume err would be true (because it is the doc) and data would be false because it is undefined.

if (err || !data)

Try using this syntax

model
  .save()
  .then((doc) => // use the doc)
  .catch((err) => // use the error)

You’re a lifesaver! Thank you so much!

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.