Model.remove not working

Tell us what’s happening:
Not quite sure what’s wrong with my code, but here’s the error it spits out.

POST
SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse ()
at /home/runner/boilerplate-mongomongoose-1/server.js:346:29
at /home/runner/boilerplate-mongomongoose-1/node_modules/mongoose/lib/model.js:4999:18
at processTicksAndRejections (internal/process/task_queues.js:79:11)

Your code so far
https://boilerplate-mongomongoose-1.kyledute.repl.co/

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.82 Safari/537.36

Challenge: Delete Many Documents with model.remove()

Link to the challenge:

As I believe I mentioned before, this is what typically happens when you try to JSON parse something that is already an object. JSON.parse is expecting a string. If you pass something that is not a string, it will convert it to a string, presumably by using the built in toString method.

const myObj = { foo: 'bar' }

console.log(myObj)
// {foo: 'bar'}

console.log(myObj.toString())
// [object Object]

console.log(JSON.parse(myObj))
// throws error: Uncaught SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse

What is happening? JSON.parse is getting that string. At position 0, it sees a “[”. No problem, JSON can be an array. It checks position 1, it is an “o”. That is impossible. There is no situation in JSON where that is a valid character in that position. The only things allowed there would be the start of a new array, the start of a new object, the start of a string (a double quote), the start of a number, the start of a boolean, or the start of null. And whitespace. Anything else is an invalid character. There are no variables in JSON so it can’t be that.

I can’t open up your repl right now for some reason. What I would recommend doing is going to the relevant JSON.parse and log out the data and type of that data on the line before. If it is not a JSON encoded string, then you should not be passing it to JSON.parse.

OK, found your repl at https://replit.com/@kyledute/boilerplate-mongomongoose-1.

So, you don’t have JSON.parse - so that must be happening somewhere else, perhaps internally in mongoose.

I don’t see anything wrong with your code. One thing I do notice is versions. In the beginning of this section you were told:

Add mongodb@~3.6.0 and mongoose@~5.4.0 to the project’s package.json

Now when I look in your package.json, I see:

        "mongodb": "^3.0.0",
        "mongoose": "^6.2.8"

Little things like that can make a big difference. Upgrading packages can break things - it should be done with caution.

Yup, changing the versions did the trick. You’re right, some of that got lost in the version control of trying to troubleshoot my previous issue. Thanks again Kevin!

1 Like

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