0

我已经使用 mongoDB 连接创建了一个数据库类,但我不知道如何在这种情况下打开一个数据库实例。

import mongo from 'mongodb'
import Grid from 'gridfs-stream'

export default class Db {
  constructor () {
    this.connection = new mongo.Db('db', new mongo.Server('127.0.0.1', 27017))
  }

  async dropDB () {
    const Users = this.connection.collection('users')
    await Users.remove({})
  }
}

我如何在课堂上使用它?

db.open(function (err) {
  if (err) return handleError(err);
  var gfs = Grid(db, mongo);
})
4

1 回答 1

0

这取决于风格,我可能尝试过类似的方法:

const { promisify } = require('util');

export default class Db {
    constructor (uri) {
            this.uri = uri || SOME_DEFAULT_DB_URL;
            this.db = null;
            this.gfs = null;
            this.connection = new mongo.Db('db', new mongo.Server('127.0.0.1', 27017));
            // Not tried but should work!
            this.connection.open = promisify(this.connection.open);
            this.connected = false;
            return this;
      }

    async connect(msg) {
            let that = this;
            if(!this.db){
                try {
                    await that.connection.open();
                    that.gfs = Grid(that.connection, mongo);                 
                    this.connected = true;
                } catch (e){
                    log.info('mongo connection error');
                }
            }
            return this;
        }

        isConnected() {
            return this.connected;
        }
}
于 2018-03-01T09:59:14.547 回答