如何在javascript类中打开mongoDB实例?

问题描述 投票:0回答:1

我使用mongoDB连接创建了一个DB类,但我不知道如何在这个上下文中打开一个db实例。

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);
})
javascript mongodb gridfs-stream
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;
        }
}
© www.soinside.com 2019 - 2024. All rights reserved.