如何删除用于Mongoose的单元测试的文档?

时间:2019-02-24 06:56:11

标签: node.js mongodb mongoose

这就是test_helper.js中的内容

const mongoose =  require('mongoose');

mongoose.Promise = global.Promise;

before((done) => {
    mongoose.connect('mongodb+srv://Minh:111g@testschedulingdb-dt089t.mongodb.net/test?retryWrites=true', { useNewUrlParser: true });
    mongoose.connection
        .once('open', () => { done(); })
        .on('error', (error) => {
         console.warn('Warning', error);
    });
});

beforeEach((done) => {
    mongoose.connection.collections.requests.drop(() => {
        done();
    });
});

如您所见,在开始新测试之前,我先删除了整个集合。如何仅删除用于测试的文档?我试过了,但是不对

beforeEach((done) => {
    mongoose.connection.collections.requests.remove((name: 'Minh') => {
        done();
    });

1 个答案:

答案 0 :(得分:1)

.remove()函数不能为null,您需要向其传递一个对象,该对象可以为空或具有过滤器;如果为空,它将从该集合中删除所有数据,并且如果有过滤器,它只会删除该元素

 mongoose.connection.collections.requests.remove({'name' :'Minh'},(err) => {
    done();
});

或者如果您要删除所有数据,

mongoose.connection.collections.requests.remove({},(err) => {
    done();
});