0

I've created a DB class using a mongoDB connection, but I don't know how to open a db instance in this context.

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({})
  }
}

How do I use this in my class?

db.open(function (err) {
  if (err) return handleError(err);
  var gfs = Grid(db, mongo);
})
user3142695
  • 15,844
  • 47
  • 176
  • 332

1 Answers1

0

It depends on style, I might have tried something like:

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;
        }
}
Zeeshan Hassan Memon
  • 8,105
  • 4
  • 43
  • 57
  • Looks nice, but I got some problems to use this class in my resolver file: `import Db from './lib/db'; const db = new Db(); db.connect(); db.collection('user')` I do not get the collection. Could you add the `dropDB` part in your answer? And similar thing with using gridfs: `var writestream = gfs.createWriteStream([options])` – user3142695 Mar 01 '18 at 11:53
  • make sure to use `await` before `async` methods like `await db.connect();`, I will update my answer in few hours bit busy atm. If you are in hurry you can see my working node-cheat here https://github.com/zishon89us/node-cheat/tree/master/gridfs/direct_upload_gridfs – Zeeshan Hassan Memon Mar 01 '18 at 12:47