我使用mongoDB连接创建了一个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);
})
答案 0 :(得分: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;
}
}