2

I am doing mocha testing. I have to connect to MongoDB in before function and I need to remove the documents in the collection in after function.

before("authenticate user", async () => {
        mongoose.connect('mongodb://localhost:27017/mo-identity')
        db = mongoose.connection;
        db.once('open', function() {
            console.log('We are connected to test `enter code here`database!')
        })
        .on('error', ()=>{console.error.bind(console, 'connection error')})
        })

    after(()=>{
        db.User.drop()
    })

Above is my code. user is a collection. While executing this code I am getting this error TypeError: Cannot read property 'drop' of undefined. Help me out this error

Ivan Vasiljevic
  • 5,478
  • 2
  • 30
  • 35
Krupanand K
  • 165
  • 2
  • 11

3 Answers3

1

I am afraid that you cannot drop collection like that:

db.User.drop()

If you want to drop collection then you should do something like this: mongoose.connection.db.dropCollection('User', function(err, result) {...});

Ivan Vasiljevic
  • 5,478
  • 2
  • 30
  • 35
  • Thank you this helps. db.User.drop() from some tutorials then it shows error. And how to remove documents in the collection. If i get answer for this it could be helpful – Krupanand K Oct 15 '18 at 12:41
0

As @drinchev said, you can remove all documents by doing this :

Model.remove({}, function(err) { 
    console.log('collection removed') 
});

In your case :

after(()=>{
    db.User.remove({}, (err) => {
      if (err) throw err;
    });
})

Hope it helps.

Sparw
  • 2,688
  • 1
  • 15
  • 34
0
/*import mongoose connection*/
const { mongodb } = require("./database/mongodb");

const collectionDrop = (collection) => {
  return new Promise(function (resolve, reject) {
    mongodb.connection.dropCollection(collection, function (err, result) {
      var success = `\n️  DropCollection '${collection}': Success!`;
      var failure = `\n️  DropCollection '${collection}' Error! ${err}`;

      if (err) {
        //if it doesn't exist, it's not an error.
        if (err.message.includes("not found")) {
          resolve(success);
        } else {
          reject(failure);
        }
      }
      if (result) {
        resolve(success);
      }
      resolve(success);
    });
  });
};

(() => {
  try {
    (async () => {
      const collections = ["users", "aaaa"];
      for (let i = 0; i < collections.length; i++) {
        const result = await collectionDrop(collections[i]);
        console.log(result);
      }
      /* In my case, I'm using it as a "pretest" script, in package.json.
            Then I close the process to proceed with the test */
      process.exit(0);
    })();
  } catch (error) {
    console.trace(error.message);
  }
})();