2017-08-14 74 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 –