Reputation: 17322
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:
{ _id: articleId }
at the beginning (right now missing in the code)collection.insertOne(articles.main)
)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
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