我希望利用Promise功能,可以同步连接到mongodb,并且可以通过将连接传递给不同的模块来重复使用它。
这是我想到的一些内容
class MongoDB {
constructor(db,collection) {
this.collection = db.collection(collection);
}
find(query, projection) {
if(projection)
return this.collection.find(query, projection);
else
return this.collection.find(query);
}
}
class Crew extends MongoDB {
constructor(db) {
super(db,'crews');
}
validate() {
}
}
我想在我的初始代码中设置一个连接,就像以下的方式,并且可以为不同的类重复使用该连接,就像mongoose或monk一样,但是只使用node-mongodb-native包。
MongoClient.connect(url)
.then( (err,dbase) => {
global.DB = dbase;
});
var Crew = new CrewModel(global.DB);
Crew.find({})
.then(function(resp) {
console.log(resp);
});
目前,db在主MongoDB类中返回undefined,我无法通过谷歌或文档进行调试。
编辑:我曾假设promise是同步的,但事实并非如此。