Ticket: Create/ Update/ Delete comments: Cannot save a comment in the mflix app

I cannot save a comment in mflix although I have passed the create/update Tickets
The >npm test -t delete-comments
is attached, gives “can post a comment” passed
and 2 errors on delete comments

the delete comment code:

try {
const deleteResponse = await comments.delete_one(
{ ‘email’: userEmail, ‘comment_id’: ObjectId(commentId) },
)
return deleteResponse
} catch (e) {
console.error(Unable to delete comment: ${e})
return { error: e }
}
}

also, when submitting a new comment, the VSC Terminal brings out a 500 error code

To me it looks like create and update a comment using _id:ObjectId(commentId) but when you delete you are using comment_id:ObjectId(commentId).

One of the two is wrong.

Well my code is as follows:

//create comments:
static async addComment(movieId, user, comment, date) {
try {
const commentDoc = {
movie_id: new ObjectId(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 }
}
}

//update comments:
static async updateComment(commentId, userEmail, text, date) {
try {
const updateResponse = await comments.updateOne(
{ ‘_id’: ObjectId(commentId), ‘email’: userEmail },
{ $set: { ‘text’: text, ‘date’: new Date(date) } }
)
return updateResponse
} catch (e) {
console.error(Unable to update comment: ${e})
return { error: e }
}
}

//delete comments:
static async deleteComment(commentId, userEmail) {
try {
const deleteResponse = await comments.delete_one(
{ ‘_id’: ObjectId(commentId), ‘email’: userEmail },
)
return deleteResponse
} catch (e) {
console.error(Unable to delete comment: ${e})
return { error: e }
}
}

and I still cannot save comments logged in under my account in the mflix app
login is successful, but the comment insert gives a error 500

Any reason why some times you use new ObjectId(…) and skme times you simply use ObjectId(…)? Like in

versus

Should it be the same?

One weekness of JS is that it is not strongly typed. So without looking at how your methods are called, I could imagine that one part of the client code pass ids as ObjectId and some other part as the string representation of ObjectId. By doing ObjectId(…) or new ObjectId() on the parameter you might end up with a runtime error.

the reason was (maybe I’m just wrong) that one of them was for creating new comments.
the other one was for updating existing comments (hence the new date)
the third iteration is also meant to delete existing comments.

I’ll experiment a bit more, I guess

still, I do not understand why the console returns OK for “can post a comment ( 285ms )” but I cannot actually save a comment in the mflix app

I mean, I get that it cannot delete my comments since i have none saved, but why it wrongly states that I can post comments?

Please post a screenshot of running

after you changed deleteComment from

to

The reason might be the following:

If the unit test calls

result = await deleteComment( "string-representing-the-comment-object-id" , ... )
// works because you do ObjectId( comment_id )

while the real code (the web interface) call

result = await deleteComment( ObjectId("string-representing-the-comment-object-id") , ... )
// does not works because comment_id is already an ObjectId

At the last minute I saw from one of your screenshot

Unable to delete comment: TypeError: comments.delete_one is not a function

Please read Delete a Document — Node.js

When we have
const deleteResponse = await comments.delete_one(
{ ‘_id’: ObjectId(commentId), ‘email’: userEmail },
)

c:\Work\mflix-js>npm test -t delete-comments

server@1.0.0 test c:\Work\mflix-js
jest --passWithNoTests “delete-comments”

Determining test suites to run…Setup Mongo Connection
(node:2020) [MONGODB DRIVER] Warning: Current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
(Use node --trace-warnings ... to show where the warning was created)
console.error
Unable to delete comment: TypeError: comments.delete_one is not a function

  104 |       return deleteResponse
  105 |     } catch (e) {
> 106 |       console.error(`Unable to delete comment: ${e}`)
      |               ^
  107 |       return { error: e }
  108 |     }
  109 |   }

  at error (src/dao/commentsDAO.js:106:15)
  at tryCatch (node_modules/regenerator-runtime/runtime.js:63:40)
  at Generator.invoke [as _invoke] (node_modules/regenerator-runtime/runtime.js:294:22)
  at Generator.next (node_modules/regenerator-runtime/runtime.js:119:21)
  at asyncGeneratorStep (node_modules/@babel/runtime/helpers/asyncToGenerator.js:3:24)
  at _next (node_modules/@babel/runtime/helpers/asyncToGenerator.js:25:9)
  at node_modules/@babel/runtime/helpers/asyncToGenerator.js:32:7

console.error
Unable to delete comment: TypeError: comments.delete_one is not a function

  104 |       return deleteResponse
  105 |     } catch (e) {
> 106 |       console.error(`Unable to delete comment: ${e}`)
      |               ^
  107 |       return { error: e }
  108 |     }
  109 |   }

  at error (src/dao/commentsDAO.js:106:15)
  at tryCatch (node_modules/regenerator-runtime/runtime.js:63:40)
  at Generator.invoke [as _invoke] (node_modules/regenerator-runtime/runtime.js:294:22)
  at Generator.next (node_modules/regenerator-runtime/runtime.js:119:21)
  at asyncGeneratorStep (node_modules/@babel/runtime/helpers/asyncToGenerator.js:3:24)
  at _next (node_modules/@babel/runtime/helpers/asyncToGenerator.js:25:9)
  at node_modules/@babel/runtime/helpers/asyncToGenerator.js:32:7

FAIL test/delete-comments.test.js
Delete Comments
√ Can post a comment (293 ms)
× Cannot delete a comment if email does not match (73 ms)
× Can delete a comment if email matches (7 ms)

● Delete Comments › Cannot delete a comment if email does not match

expect(received).toBe(expected) // Object.is equality

Expected: 0
Received: undefined

  53 |     )
  54 |
> 55 |     expect(deleteCommentResult.deletedCount).toBe(0)
     |                                              ^
  56 |   })
  57 |
  58 |   test("Can delete a comment if email matches", async () => {

  at toBe (test/delete-comments.test.js:55:46)
  at tryCatch (node_modules/regenerator-runtime/runtime.js:63:40)
  at Generator.invoke [as _invoke] (node_modules/regenerator-runtime/runtime.js:294:22)
  at Generator.next (node_modules/regenerator-runtime/runtime.js:119:21)
  at asyncGeneratorStep (node_modules/@babel/runtime/helpers/asyncToGenerator.js:3:24)
  at _next (node_modules/@babel/runtime/helpers/asyncToGenerator.js:25:9)

● Delete Comments › Can delete a comment if email matches

expect(received).toBe(expected) // Object.is equality

Expected: 1
Received: undefined

  62 |     )
  63 |
> 64 |     expect(deleteCommentResult.deletedCount).toBe(1)
     |                                              ^
  65 |   })
  66 | })
  67 |

  at toBe (test/delete-comments.test.js:64:46)
  at tryCatch (node_modules/regenerator-runtime/runtime.js:63:40)
  at Generator.invoke [as _invoke] (node_modules/regenerator-runtime/runtime.js:294:22)
  at Generator.next (node_modules/regenerator-runtime/runtime.js:119:21)
  at asyncGeneratorStep (node_modules/@babel/runtime/helpers/asyncToGenerator.js:3:24)
  at _next (node_modules/@babel/runtime/helpers/asyncToGenerator.js:25:9)

Test Suites: 1 failed, 1 total
Tests: 2 failed, 1 passed, 3 total
Snapshots: 0 total
Time: 3.655 s
Ran all test suites matching /delete-comments/i.
Teardown Mongo Connection
npm ERR! Test failed. See above for more details.


||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
however, when
const deleteResponse = await comments.delete_one(
{ ‘email’: userEmail, ‘comment_id’: ObjectId(commentId) },
)

I get:
code: ‘BABEL_PARSE_ERROR’,
reasonCode: ‘InvalidOrUnexpectedToken’
}
[nodemon] app crashed - waiting for file changes before starting…

in the VSC Terminal,
and,
in cmd:

c:\Work\mflix-js>npm test -t delete-comments

server@1.0.0 test c:\Work\mflix-js
jest --passWithNoTests “delete-comments”

Determining test suites to run…Setup Mongo Connection
(node:3316) [MONGODB DRIVER] Warning: Current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
(Use node --trace-warnings ... to show where the warning was created)
FAIL test/delete-comments.test.js
● Test suite failed to run

Jest encountered an unexpected token

Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

By default "node_modules" folder is ignored by transformers.

Here's what you can do:
 • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
 • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
 • If you need a custom transformation specify a "transform" option in your config.
 • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation

Details:

SyntaxError: C:\Work\mflix-js\src\dao\commentsDAO.js: Unexpected character '‘'. (102:10)

  100 |       // Use the userEmail and commentId to delete the proper comment.
  101 |       const deleteResponse = await comments.delete_one(
> 102 |         { ‘email’: userEmail, ‘comment_id’: ObjectId(commentId) },
      |           ^
  103 |         )
  104 |       return deleteResponse
  105 |     } catch (e) {

  at Parser._raise (node_modules/@babel/core/node_modules/@babel/parser/src/parser/error.js:134:45)
  at Parser._raise [as raiseWithData] (node_modules/@babel/core/node_modules/@babel/parser/src/parser/error.js:129:17)
  at Parser.raiseWithData [as raise] (node_modules/@babel/core/node_modules/@babel/parser/src/parser/error.js:78:17)
  at Parser.raise [as getTokenFromCode] (node_modules/@babel/core/node_modules/@babel/parser/src/tokenizer/index.js:978:16)
  at Parser.getTokenFromCode [as nextToken] (node_modules/@babel/core/node_modules/@babel/parser/src/tokenizer/index.js:300:12)
  at Parser.nextToken [as next] (node_modules/@babel/core/node_modules/@babel/parser/src/tokenizer/index.js:163:10)
  at Parser.next [as parseObjectLike] (node_modules/@babel/core/node_modules/@babel/parser/src/parser/expression.js:1845:10)
  at Parser.parseObjectLike [as parseExprAtom] (node_modules/@babel/core/node_modules/@babel/parser/src/parser/expression.js:1166:21)
  at Parser.parseExprAtom [as parseExprSubscripts] (node_modules/@babel/core/node_modules/@babel/parser/src/parser/expression.js:652:23)
  at Parser.parseExprSubscripts [as parseUpdate] (node_modules/@babel/core/node_modules/@babel/parser/src/parser/expression.js:632:21)

Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 2.681 s, estimated 3 s
Ran all test suites matching /delete-comments/i.
Teardown Mongo Connection
npm ERR! Test failed. See above for more details.

I really do not know how to say it differently. I write that you have an error that says:

and I point you to the correct function:

And yet you submit a new post with the same code:

with wrong quotes:

First, make sure you use the appropriate quotes. Type them by hand. Do not cut-n-paste unless you know exactly the difference between quote types.

Second, just to be clear delete_one is not a function.

1 Like

thanks to pointing me to what obviously is a case of syntactic fatigue/blindness.
I just assumed I wrote that correctly and I was looking in other parts of the code for mistakes.

Thank you for the help, Steeve J.

The Ticket: Delete Comments passed.
The rest of the Chapter 2 passed previously too.

However, the other half of the problem persists. I still get
POST /api/v1/movies/comment 500 1.072 ms - 8
error when trying to submit a comment in mflix.

I have checked the integrity of the comments.controller.js versus the original in the archive and found no accidental changes.

Facing the same issue of 500 error code. Not able to add a comment, And getting the status “Create/Update Comments: Unable to update comment”.
I’m confused that if I was not able to add a comment then how this status is showing - Unable to update. Code is proper as I tried with another dummy app. Please help.

Please check if the following might be the appropriate solution for the 500 error code:

1 Like