Home > Enterprise >  Connecting to mongodb in nodejs
Connecting to mongodb in nodejs

Time:03-15

I am first to use MongoClient to connect mongodb in nodejs, in each js file I use it like following

'use strict'
//part 1
const { MongoClient } = require('mongodb');
const dbconfig = require('../config/index');
const Mongodb = {
    client: new MongoClient(dbconfig.product.dbUrl, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
    }),
    oper: null,
    db: null,
    dbName: '',
};
const dbConnect = async (dbName = dbconfig.product.dbName) => {
    if (Mongodb.oper) {
        if (dbName !== Mongodb.dbName) {
        Mongodb.db = Mongodb.client.db(dbName);
        Mongodb.dbName = dbName;
        }
        return Mongodb.db;
    }
    Mongodb.oper = await Mongodb.client.connect();
    return await dbConnect(dbName);
};

//part 2
const db = await dbConnect();
let info = await db.collection.find({});
//more code

The situation is that there is a lot of duplicate code, such as part 1, and I want to put part 1 into a file and import it where needed. I have no idea how to do, give me some ideas please, thank you.

CodePudding user response:

You only need to connect to db once. My advice would be - google and try mongoose. I find it easier. Google some examples and read the docs.

CodePudding user response:

Create a JS module that exports the connect function using module.exports then require it where necessary, something like this:

// mongo.js
const { MongoClient } = require('mongodb');
const dbconfig = require('../config/index');

const client = new MongoClient(dbconfig.product.dbUrl, {
    useNewUrlParser: true,
    useUnifiedTopology: true
});

let databasePromise;

async function _connect() {
    try {
        await client.connect();
    } catch (e) {
        console.error(e);
        await closeConnection();
        throw e;
    }
    return client.db();
}

function connect() {
    if (!databasePromise) {
        databasePromise = _connect();
    }
    return databasePromise;
}

async function close() {
    await client.close();
    databasePromise = undefined;
}

isConnected() {
    return client.isConnected();
}

module.exports = {
    connect,
    close,
    isConnected,
}


// index.js
const { connect } = require('./mongo');

(async () => {
    const db = await connect();
    const results = await db.collection('collection1').find({});
    console.log(results);
})();


// file2.js
const { connect } = require('./mongo');

(async () => {
    const db = await connect();
    const results = await db.collection('collection2').find({});
    console.log(results);
})();

Note, this code is not tested so it might need adjustments.

  • Related