NodeJS / MongoDB:只连接一次到数据库

我正在做一些nodeJS应用程序的e2etesting。 在钩子之前/之后,我需要添加/删除一些mongoDB文件,这是我做的:

不应该只能连接一次到mongo服务器吗?

我想做什么:

  1. 在开始处删除所有文档{ _id: articleId } (现在在代码中缺less)
  2. 将新文档插入到数据库( collection.insertOne(articles.main)
  3. testing完成后删除所有文件

我的代码感觉不是很好

 describe('article module', function () { before(function () { MongoClient.connect(mongoServer, (err, db) => { expect(err).to.be.null db.collection('content', (err, collection) => { expect(err).to.be.null collection.findOne({ _id: articleId }, (err, item) => { expect(err).to.be.null if (!item) collection.insertOne(articles.main) db.close() }) }) }) }) after(function () { MongoClient.connect(mongoServer, (err, db) => { expect(err).to.be.null db.collection('content', (err, collection) => { expect(err).to.be.null collection.remove({ _id: articleId }, (err, removed) => { expect(err).to.be.null db.close() }) }) }) }) }) 

 describe('article module', () => { before(() => { MongoClient.connect(mongoServer, (err, db) => { expect(err).to.be.null const content = db.collection('content'); content.findOne({ _id: articleId }) .then(item => { return content.insertOne(articles.main); }) .then(insertResult => { db.close(); }) .catch(err => { expect(err).to.be.null; }) }) }) after(() => { MongoClient.connect(mongoServer, (err, db) => { expect(err).to.be.null const content = db.collection('content'); content.remove({ _id: articleId }) .then(removed => { db.close(); }) .catch(err => { expect(err).to.be.null; }) }) }) }) 

你也可以使用第三方的promise来调用db