Good afternoon I ended up making a crossed comment believe that because for a long time I haven't used the native driver, good we'll go there one way to load the driver with the connection is using https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Promise for return of the connection in the callback:Mongo. jHere in our file mongo.js where we connect to the mongodb instance, but we still do not connect 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. jNow in our index we will call our promise: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 is the following I invoke our promise and add await to expect our promise to be resolved or rejected, remembering that await only have use in defined function as async and our method is a promise other detail without trycatch there is no way to capture and treat the error of our promise and its application would crash. After solving our connection I have the db that is where our connection in the instant 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 perform two actions, one of creating a collection and another of inserting an item in the created collection, I am a little rusty with the native driver, I was very dependent on the mongoose, but there is a hint of how to load the connection to your files.For your example would be the 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 that I set up did not realize the connection predicted to the bank of collections to be able to export db that has the method db.close().