Good afternoon I ended up making a cross comment I believe that because it has been a long time that I do not use the native driver, well let’s there one of the ways to load the driver with the connection is using Promise for connection return in callback:
Mongo.js
Here in our archive mongo.js
where we make the connection to mongodb instance, but not yet connected to our Collections bank:
const MongoClient = require('mongodb').MongoClient
const url = 'mongodb://localhost:27017'
module.exports.connectMongodb = async() => {
return new Promise((resolve, reject) => {
MongoClient.connect(url,{ useNewUrlParser: true }, (err, db) => {
if(err) return reject('Não foi possivel se conectar a instância!!')
console.log('instance connected')
resolve(db)
})
})
}
index js.
Now in our index we will call our Precedent:
const {connectMongodb} = require('./mongo')
const start = async() => {
try {
const db = await connectMongodb()
const dbo = db.db('mydboMongo')
dbo.createCollection('user', (err, dbs) => {
if(err){
return console.log(err)
}
console.log('collection created')
db.close()
})
dbo.collection('user').insertOne({
username: 'carlos',
disabled: '2'
}, (err, res) => {
if(err){
console.log(err)
}
console.log('document inserted')
db.close()
})
} catch (error) {
console.log(error.message)
}
}
start()
Here occurs the following I invoke our Precedent and add await
to wait for our trial to be resolved or rejected, remembering that await will only have use in Function defined as async
and our way is to select another detail without the trycatch there is no way to capture and treat the error of our Promise and its application would crash.
After the solution of our connection I have db which is where our connection at the instance then we make the connection to our Collections bank db.db('mydboMongo')
remembering that here it connects or creates our bank if it already exists it just connects.
After being connected we performed two actions, one to create a collection and another to insert an item in the collection created, I’m a little rusty with the native driver, I became very dependent on Mongoose, but there is a tip on how to load the connection to your files.
For your example would look like this connection:
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'myproject';
// Create a new MongoClient
const client = new MongoClient(url);
// Use connect method to connect to the Server
module.exports.connectMongo = async() => {
return new Promise(function(resolve, reject){
client.connect(function(err, db) {
//assert.equal(null, err);
if(err) return reject('Could not connect.')
console.log("Connected successfully to server");
resolve(db)
});
})
}
In the example I set the above I did not perform the connection provided to the Collections database to be able to export db that has the method db.close()
.
Just export the
client
and import where you want to use.– Chance
But then I’ll have to write client.connect all the time, and if one day I want to update the bank to a newer driver?
– JeffersonCarlosBD