user3142695
user3142695

Reputation: 17322

NodeJS/MongoDB: Only connect one time to DB

I'm doing some e2e tests of a nodeJS application. In the before/after hooks I need to add/remove some mongoDB documents and this is how I do that:

Shouldn't it be possible to connect only one time to the mongo server at all?

What I would like to do:

  1. Remove all documents { _id: articleId } at the beginning (right now missing in the code)
  2. Insert new document to DB (collection.insertOne(articles.main))
  3. Remove all documents after the tests has be finished

My code feels not very good to me

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()
        })
      })
    })
  })
})

Upvotes: 1

Views: 355

Answers (1)

Avindu Hewa
Avindu Hewa

Reputation: 1788

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

You can call the db using a third party promise as well

Upvotes: 1

Related Questions