2017-08-14 75 views
1

我正在做一些nodeJS应用程序的e2e测试。在挂钩之前/之后,我需要添加/删除一些mongoDB文档,这是我的方式:NodeJS/MongoDB:只连接一次数据库

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

我想这样做:

  1. 删除开头的所有文件{ _id: articleId }(现在的代码所缺少)
  2. 插入新的文档DB(collection.insertOne(articles.main)
  3. 后删除所有文件测试已完成

我的代码感觉不是我

非常好
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() 
     }) 
     }) 
    }) 
    }) 
}) 
+0

只是把它变成一个功能,调用该函数................. .......... – Eric

+0

你实际上可以使用承诺来链接它,它会使它更清洁 –

+0

@AvinduHewa你可以发布代码示例吗? – user3142695

回答

1
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; 
     }) 
    }) 
    }) 
}) 

您可以使用第三方的承诺,以及调用数据库

+0

感谢你的例子。 downvote不是我的... – user3142695

+0

我希望它有帮助,但我不明白downvote –