猫鼬返回一个空数组

时间:2018-11-25 12:28:59

标签: javascript node.js mongodb mongoose

当我尝试使用find()函数时,猫鼬返回一个空数组。有人可以帮我吗?

users.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;    
mongoose.Promise = global.Promise;

const userSchema = new Schema({
    name: String    
});
const user = mongoose.model('user', userSchema, 'users');    
module.exports = user;

test_helper.js

   const mongoose = require('mongoose');

    mongoose.connect('mongodb://localhost/user_test');

    before((done)=>{
        mongoose.connection.once('open',()=>{
            console.log('Connected');
        }).on('error', ()=>{
            console.log('Error');
        });
        done();
    });

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

create_user.js

const assert = require('assert');
const User = require('../src/user');


describe('Create a user',()=>{
    it('it should create a new user',(done)=>{
        let joe = new User({
            name : "Joe"
        });
        joe.save().then(()=>{
            assert(!joe.isNew);
            done();
        });
    });
})

reading-users.js

const assert = require('assert');
const User = require('../src/user');


describe('This will read all users', () => {
    before((done) => {
        joe = new User({name:'joe'});
        joe.save().then(() => done());
    });
    it('It Should find all users named joe', (done) => {
        User.findOne({name:"Joe"})
            .then((foo)=>{
                //assert(users[0]._id.toString()===joe._id.toString());
                console.log(foo);
                console.log(joe);
                done();
        });
    });
});

=================================================== =======================

  

(节点:3324)DeprecationWarning:当前URL字符串解析器为   已过时,将在以后的版本中删除。使用新的   解析器,将选项{useNewUrlParser:true}传递给MongoClient.connect。   创建一个已连接的用户       √应该创建一个新用户(274ms)

     

这将读取所有用户     [] {_id:5bfa98eb6bd05d0cfc5d639d,名称:     'joe',__v:0}       √应该找到所有名为joe的用户

     

2个通过(1s)

1 个答案:

答案 0 :(得分:1)

此问题的根本原因是,每次启动测试时,创建的记录将始终在测试开始之前被删除。这是在beforeEach文件中的test_helper.js块内发生的。尝试将beforeEach替换为afterEach

afterEach((done)=>{
    mongoose.connection.collections.users.drop(()=>{
        done();
    });
});