Model.remove()&deleteMany() solution not working

The error I was receiving was :

(node:998) [MONGODB DRIVER] Warning: collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead.
SyntaxError: Unexpected token o in JSON at position 1
    at JSON.parse (<anonymous>)
    at /home/runner/boilerplate-mongomongoose/server.js:346:29
    at /home/runner/boilerplate-mongomongoose/node_modules/mongoose/lib/model.js:4919:18
    at processTicksAndRejections (internal/process/task_queues.js:79:11)

So I assumed that remove() and deleteMany() were returning an object instead of a string. So I changed my code to :

const removeManyPeople = (done) => {
  const nameToRemove = "Mary";
  Person.deleteMany({name: nameToRemove}, (err, response) => {
    if(err) return console.error(err);
    console.log(JSON.stringify(response))
    done(null, JSON.stringify(response));
  })
};

which returned successful delete POST without error. However, the test still FAILS and I cannot pass the test. How can I fix this?:

Your app is listening on port 3000
OPTIONS
POST
(node:1069) [MONGODB DRIVER] Warning: collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead.
{"deletedCount":2}

Your project link(s)

solution: https://replit.com/@catherineyang2/boilerplate-mongomongoose

Your browser information:

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

Challenge: Delete Many Documents with model.remove()

Link to the challenge:

2 Likes

First check this SO answer about this error
https://stackoverflow.com/questions/38380462/syntaxerror-unexpected-token-o-in-json-at-position-1?rq=1

If you check the code at server.js line 346 it’s in an if statement

if (data.ok === undefined) {

The code expects an ok property and if it’s not present, it tries to parse the data as json.
The problem here is that data is already an object, it’s not a string. So string form of the data is [object Object] and the first o is causing the Unexpected token o in JSON at position 1 error.

As as workaround you can try this:

const removeManyPeople = (done) => {
  const nameToRemove = "Mary";
  Person.remove({name:nameToRemove},(err,data)=>{
    if(err) return console.error(err);
    data.ok = true;
    data.n = data.deletedCount;
    done(null , data);
  });
};

data.ok is for the aforementioned if statement and data.n is for server.js line 353.

11 Likes

I would suggest checking your versions for Mongoose and MongoDB. I recently had this issue and it’s being updated to show the correct versions in the curriculum.

6 Likes

I had the same problem, it works for me ,
thanks for your help. :wink:

1 Like

I had a similar issue.
Your suggesteed solution worked for me.
Thank you.

1 Like

Another solution will be just to use Model.deleteMany() instead of Model.remove(). That one worked for me.

worked for me
but do you know what is the cause for this ?
is it the mongoose version ?