【问题标题】:How can I clear my MongoDB collection between Mocha tests? Collection.remove({}) isn't working. . . [duplicate]如何在 Mocha 测试之间清除我的 MongoDB 集合? Collection.remove({}) 不起作用。 . . [复制]
【发布时间】:2018-02-22 18:09:39
【问题描述】:

如何在 Mocha 测试之间清除我的 MongoDB 集合? Collection.remove({}) 不起作用。 . . .

有人知道我做错了什么吗?

我也用这种语法尝试过User.remove({}),但无济于事。

另外,如果您有时间,这似乎是编写此测试的合理方式吗?诚然,我是测试新手。

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);
          });
        }
      );
    });

【问题讨论】:

  • 我不认为这是重复的。那个人的问题的解决方案在我的情况下不起作用。
  • Collection.drop()

标签: javascript node.js mongodb mocha.js


【解决方案1】:

你想使用deleteMany

根据具体情况,您可能希望清空数据库 beforeAllafterAll 规范,而不是 beforeEachafterEach em> 规格。

另外,请确保您使用的是测试数据库,而不是使用生产或开发数据库进行测试。

User.deleteMany({}, (err) => console.log(err));

【讨论】:

  • 这也不起作用。我仍然收到重复的键错误。
  • config/config 发生了什么?
  • 它提供`'数据库':process.env.DATABASE_URL || 'mongodb://localhost:27017/blah',` 变成mongoose.connect
猜你喜欢
  • 2018-10-29
  • 1970-01-01
  • 1970-01-01
  • 2021-01-08
  • 1970-01-01
  • 1970-01-01
  • 2014-06-02
  • 1970-01-01
  • 2018-08-06
相关资源
最近更新 更多