我正在做一些nodeJS应用程序的e2e测试。在挂钩之前/之后,我需要添加/删除一些mongoDB文档,这是我的方式:NodeJS/MongoDB:只连接一次数据库
不应该只能连接一次到mongo服务器吗?
我想这样做:
- 删除开头的所有文件
{ _id: articleId }
(现在的代码所缺少) - 插入新的文档DB(
collection.insertOne(articles.main)
) - 后删除所有文件测试已完成
我的代码感觉不是我
非常好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()
})
})
})
})
})
只是把它变成一个功能,调用该函数................. .......... – Eric
你实际上可以使用承诺来链接它,它会使它更清洁 –
@AvinduHewa你可以发布代码示例吗? – user3142695