MongoDB and Mongoose - Delete Many Documents with model.remove()

code not working. I am working in local system

package.json

"dependencies": {
    "body-parser": "^1.15.2",
    "dotenv": "^8.2.0",
    "express": "^4.18.2",
    "mongodb": "^3.6.0",
    "mongoose": "^5.4.0"
  }

myApp.js

const personSchema = new mongoose.Schema({
   name: {
      type: String
   },
   age: {
     type: Number
   },
   favoriteFoods: [{
     type: String
   }]
});

const removeManyPeople = (done) => {
   const nameToRemove = "Mary";

   Person.remove({name: nameToRemove}, (err, data) => {
      if(err){done(err)}
      done(null, data);
      })
};

Challenge: MongoDB and Mongoose - Delete Many Documents with model.remove()

Link to the challenge:

I have cloned the given repo again. I have been running it on local system but it’s still not working.

GitHub - https://github.com/antu99g/freeCodeCamp-mongoDB

local console :

Your app is listening on port 3000
OPTIONS
POST
(node:10144) DeprecationWarning: collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead.
(Use `node --trace-deprecation ...` to show where the warning was created)
[object Object]

test error on freeCodeCamp :

[Error: E11000 duplicate key error collection: freeCodeCamp_task.people index: name_1 dup key: { name: "Mary" }]

You likely had it set as unique in the Schema at one point. Delete the collection on Atlas and try the submit again (still without using unique in the Schema).

No, I have not set any value for unique in my Schema.
This is my Schema :

const mongoose = require('mongoose');
mongoose.connect(process.env.MONGO_URI);

const personSchema = new mongoose.Schema({
  name: {
    type: String
  },
  age: {
    type: Number
  },
  favoriteFoods: [{
    type: String
  }]
});

let Person = mongoose.model('Person', personSchema);

It doesn’t matter how the Schema looks now. Are you sure you at some point didn’t use unique: true?

At least that is one reason I know of for the error you are getting.

[Error: E11000 duplicate key error collection: freeCodeCamp_task.people index: name_1 dup key: { name: "Mary" }]

Did you try to do what I said? Delete the collection (click the delete icon next to the collection) then try the submission again.

I encountered same error, and after deleting the collection and re-running, it worked for me. No idea why it works now, Can someone explain?

Yes, I had unique: true in my Schema. I had to created another collection and that worked…thanks.

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