mongodb nodejs db.collection不是一个函数

时间:2017-12-22 07:34:22

标签: node.js mongodb ecmascript-6 typeerror

这是我的FollowerModel类(在ES6中),表示我的MongoDB的follower集合

import mongo from 'mongodb';

class FollowerModel {

    constructor(db, logger) {
        this._db = db;
        this._logger = logger;
    }

    async create(data) {
        try {
            data._id = mongo.ObjectID().toString();
            return await this._db.collection('follower').insertOne(data);
        } catch (error) {
            return Promise.reject(error);
        }
    }

}

export default FollowerModel;

这是我的单元测试

import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
import { expect } from 'chai';
import mongo from 'mongodb';
import mongo_url from '../../config/mongodb';
import logger from '../../config/logger';
import to from 'await-to-js';
import FollowerModel from '../../model/follower';

const MongoClient = mongo.MongoClient;
const data = {
    email: 'my_email',
    phone: 'my_phone',
    code: 'my_code'
};

describe('Model: Follower', () => {

    let Follower;
    let connected = false;
    let _db;

    const connect = () => {
        try {
            const db = await MongoClient.connect(mongo_url);
            Follower = new FollowerModel(db, logger);
            connected = true;
            _db = db;
            return Promise.resolve();
        } catch (error) {
            return Promise.reject(error);
        }
    };

    before(() => connect());

    describe('create', () => {
        let _id;
        beforeEach(() => connected ? null : connect());
        it('Returns with insertedId', async () => {
            const [, result] = await to(Follower.create(data));
            return expect(result).to.have.property('insertedId');
        });
        afterEach(() => connected ?
            _db.collection('follower').deleteOne({ _id }) : connect().then(() => _db.collection('follower').deleteOne({ _id }))
        );
    });

});

此测试失败,错误this._db.collection is not a function让我很沮丧。在我初始化Follower实例时,db被传递给构造函数,在类中成功初始化db。我甚至试过console.log dbdb.collection。它会按预期记录db,但会为undefined返回db.collection。这让我很困惑

1 个答案:

答案 0 :(得分:1)

自MongoDB本机NodeJS驱动程序的V3 +以来:

const db = await MongoClient.connect(mongo_url);

_db = db.db("nameOfyourDataBase");

//then you can use _db.collection