0

How can I clear my MongoDB collection between Mocha tests? Collection.remove({}) isn't working. . . .

Does anyone see what I could be doing wrong?

I've tried User.remove({}) with this syntax, as well, to no avail.

Also, if you have a moment, does this seem like a reasonable way to write this test? I'm admittedly new to testing.

const User = require('../../../app/models/user');
const config = require('../../../config/config');
const mongoose = require('mongoose');
const chai = require('chai');
const chaiAsPromise = require('chai-as-promised');
const sinon = require('sinon');
const expect = chai.expect;
chai.use(chaiAsPromise);
mongoose.connect(config.database, { useMongoClient: true });
mongoose.Promise = global.Promise;

describe('The user model', () => {
  describe('during creation', () => {
    beforeEach(() => {
      // Clear the User collection of all users.
      User.remove({}, () => {});
    });
    afterEach(() => {
      // Clear the User collection of all users.
      User.remove({}, () => {});
    });

    it('should store the user in the database', () => {
      let userData = {
        email:    'blah@user.com',
        password: '1234'
      };
      let user = new User(userData);

      return user.save().then(
        newUser => {
          return User.findOne({_id: newUser._id}, (error,retrievedUser) => {
            let expected = newUser._id;
            let actual = retrievedUser._id;

            console.log(actual,expected);
            return expect(actual).to.equal(expected);
          });
        }
      );
    });
Michael P.
  • 1,373
  • 3
  • 12
  • 33

1 Answers1

0

You want to use deleteMany.

Depending on the case, you may want to empty the database beforeAll and afterAll specs rather that beforeEach and afterEach spec.

Also, ensure that you're using a testing database and not testing with a production or development database.

User.deleteMany({}, (err) => console.log(err));
Oluwafemi Sule
  • 36,144
  • 1
  • 56
  • 81