Personal Library test 5

For some reason that I can not figure out I am failing the following test.

You can send a POST request containing comment as the form body data to /api/books/{_id} to add a comment to a book. The returned response will be the books object similar to GET /api/books/{_id} request in an earlier test. If comment is not included in the request, return the string missing required field comment . If no book is found, return the string no book exists .

When I run my site it seems to do exactly what the test is asking for. If someone types in an invalid Id it responds with “no book exists”. If someone types in a correct Id and no comment is given it responds with “missing required field comment”. It seems to do be working correctly, but still won’t pass.

When I log the FCC site after submitting solution this error message pops up:
Error: expected { Object (comments, _id, …) } to be a string.

So, it seems like I return an updated object instead of an error message on a specific case, but I am not sure.

here is the post route I am using.

    .post((req, res) => {
      let bookId = req.params.id;
      let comment = req.body.comment;
      if (comment == "") return res.json("missing required field comment");

      Book.findByIdAndUpdate(
        bookId,
        { $push: { comments: comment }, $inc: { commentcount: 1 } },
        { new: true }, // {new, true} returns the updated version and not the original. (Default is false)
        (error, updatedBook) => {
          if (error) return res.json("no book exists");

          if (!updatedBook) return res.json("no book exists");
          else return res.json(updatedBook);
        }
      );
    })

Here is a link to the app I am using

solution: https://personal-library-project.herokuapp.com

Thank you for your help in advance!
Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.3 Safari/605.1.15.

Challenge: Personal Library

Link to the challenge:

When you’re calling an API the non-provided parameter (comment) won’t be an empty string, it’ll be undefined.

1 Like

Thank you kind soul. Changed it to if (!comment) and it passed the test now.

When I used console.log(comment) it returned an empty string. This is why I am confused on why it is undefined instead when calling an API.

When you’re submitting request via form, empty values are empty strings (default value for <input> element).
When you’re calling an API, you’re submitting parameters in the request body as a JSON, something like this:

{
  "name": "John",
  "age": 42
}

and then when you try to read some key that is not provided (e.g. “address”), it’ll be undefined (or in this particular case the test is submitting an empty object, and you’re trying to read the comment key).

1 Like

That makes sense, thank you for clearly explaining this! Saved me a lot of time.