Reputation: 3465
I'm building my Node.js application by Express. I have two choices to write code in order to connect to my MongoDB.
Then
function productRepository(db) {
this.db = db;
};
productRepository.prototype.insert = function(item) {
return new Promise((resolve, reject) => {
this.db.collection('product').insertOne(item, function(err, result) {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
};
module.exports = productRepository;
And
module.exports = function(app, db) {
var productRepository = require('../model/product');
var productRepoInstance = new productRepository(db);
app.get('/test', function(req, res) {
productRepoInstance.insert({ createdAt: new Date() }).then(
(result) => res.send({ result: 1 }),
(error) => {
console.log(error);
res.send({ result: 0 });
});
});
};
I wonder which is better, and why?
Upvotes: 1
Views: 1717