Chapter 2: User-Facing Backend Ticket: Create/Update Comments

Hello!
It says it successfully inserted the document,

postCommentResult: [
{
movie_id: ‘573a13b9f29313caabd4ddff’,
name: ‘foobar’,
email: ‘foobar@baz.com’,
text: ‘fa-fe-fi-fo-fum’,
date: 2022-09-20T22:55:28.438Z,
_id: 632a44e003547c20fc89fe61
}
]
at log (test/create-update-comments.test.js:53:13)

console.log
insertedCount: 1
at log (test/create-update-comments.test.js:54:13)

console.log
insertedId: 632a44e003547c20fc89fe61
at log (test/create-update-comments.test.js:55:13)

It’s not showing up the comments collection via compass and the comments array is empty in the movies collection.

console.log
movieComments:

Here is my code:

static async addComment(movieId, user, comment, date) {
try {
const commentDoc = { “movie_id”:movieId, “name”:user.name, “email”:user.email, “text”: comment, “date”:date }
return await comments.insertOne(commentDoc)
} catch (e) {
console.error(Unable to post comment: ${e})
return { error: e }
}
}

static async getMovieByID(id) {
try {
console.log("getMovieByID: ", id);
const pipeline = [
{
$match: {
_id: ObjectId(id)
}
},

    {
      $lookup: {
        from: "comments",
        let: {
            id: "$_id",
        },
        pipeline: [
            {
                $match: {
                    $expr: {
                        $eq: ["$movie_id", "$$id"],
                    },
                },
            },
            {
                $sort: {
                    date: -1,
                },
            },
        ],
        as: "comments"
      }
    },

  ]

  return await movies.aggregate(pipeline).next()
} catch (e) {
  console.error(`Something went wrong in getMovieByID: ${e}`)
  throw e
}

}

This seems to indicate that you are running a unit test. Most likely, you do not see the comment because the unit test makes sure it returns the database in a sane state in case you wish (and you should) run the test multiple times. If it (the unit test) leaves the comment in the DB, the unit test would now fails every times unless you manually remove the comment. You do not want to do manual intervention during unit tests…

1 Like

@steevej
That makes sense. I am running the create-update-comments unit test

So, I am successfully inserting the document.
The next step is
const movieComments = (await MoviesDAO.getMovieByID(movieId)).comments
which is an empty array

If you get an empty array in getMovieByID then either getMovieByID is wrong or the comment is not inserted correctly.

Make sure that what ever field is used when inserting the comment is written exactly as it is expected in getMovieByID and make sure that what the types (most likely it is an ObjectID) are the same in both collections.

@steevej

Thanks for the hint!! I kept looking but not seeing what I was doing wrong!!
I re-read your response and found that I didn’t wrap my id

Thanks!!

1 Like