How to manipulate Mongodb out of the configuration file?

Asked

Viewed 102 times

0

I am studying Nodejs and Mongodb, I can even make the connection and some tests in the bank, but I would like to be able to export the connection with the bank to be able to do Insert/find/remove/etc from anywhere in my application, like a module.:

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

var banco;
// Use connect method to connect to the Server
client.connect(function(err) {
    assert.equal(null, err);
    console.log("Connected successfully to server");

    banco = client.db(dbName);
});

module.exports = banco;

but obviously... it doesn’t work!

  • Just export the client and import where you want to use.

  • 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?

2 answers

0

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

0


I ended up opting for the package express-Mongo-db, not quite what I wanted, but with about 3 lines of code it was possible to call the bank to each request:

var app = require('express')();

var expressMongoDb = require('express-mongo-db');
app.use(expressMongoDb('mongodb://localhost/test'));

app.get('/', function (req, res, next) {
    req.db // => Db object
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.