skip to Main Content

I don’t know If I’m checking for the value of the boolean correctly

what this code does: the user creates a note for himself, his ID is on the note and it needs to belong to a category name that has to be in the category schema ( where my error happens )

exports.postAddNote = (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    const error = new Error("validation failed, entered data is incorrect");
    throw error;
  }
  const content = req.body.content;
  const tags = req.body.tags;
  const categoryName = req.body.categoryName;
  let creator;
  const note = new Note({
    content: content,
    categoryName: categoryName, //  work
    tags: tags,
    creator: req.userId,
  });
  Category.find()
    .select("-_id")
    .select("-__v")
    .select("-notesId")
    .then((categories) => {
      console.log(categories); //stripping everything but names off categories
      const CategoryExists = categories.some(
        (category) => category.name === categoryName
      );
      console.log(CategoryExists); // ~~~~~~~~~~ this logs correctly
      if (CategoryExists === -0) { // ~~~~~~~~~~ what i want: if the value is false
        return res.json({ Error: "The category you entered does not exist" });
      } 
      note // ~~~~~~~~~~ the code stops here :/ it doesn't save the note
        .save()
        .then((note) => {
          console.log("saved note");
          User.findById(req.userId);
        })
        .then((user) => {
          creator = user;
          user.notes.push(note);

          return user.save();
        })
        .then((result) => {
          res.status(201).json({
            info: {
              dateCreated: new Date().toISOString(),
              status: "Note Created Successfully",
              creator: { _id: creator._id, email: creator.email },
            },
          });
        })
        .catch((err) => {
          if (!err.statusCode) {
            err.statusCode = 500;
          }
        });
    })
    .catch((err) => {
      console.log(err);
      next();
    });
};

2

Answers


  1. if (CategoryExists === -0)
    

    should be

    if (CategoryExists === false)
    

    or just

    if (!CategoryExists)
    

    i believe. did you try that? not sure why you are using -0. the return value for some() is either going to be true or false.

    Login or Signup to reply.
  2. try this:

     if (!CategoryExists) {
            return res.json({ Error: 'The category you entered does not exist' });
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search