Click here to Skip to main content
15,434,104 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
For my express.js project, I use the migrate package to manage the Models of my Mongo database.
I defined database object in db.js file.Then I used it in migrate file.
//db.js file
const mongoClient = require('mongodb').MongoClient;
    const mongoDbUrl = 'mongodb://127.0.0.1:27017/mydb';
    let mongodb;

    function connect(callback){
        mongoClient.connect(mongoDbUrl, (err, db) => {
            mongodb = db;
            callback();
        });
    }
    function get(){
        return mongodb;
    }

    function close(){
        mongodb.close();
    }

    module.exports = {
        connect,
        get,
        close
    };


'use strict'
// db is just an object shared between the migrations
var myDB = require('../db/db.js');


module.exports.up = function (next) {

  myDB.connect(function (err, client) {
    if (err) {
      console.log(err);
    }
    else {
      // start the rest of your app here
      
    }

  });

  console.log("MyDB=" + myDB.get());

  next()
}

module.exports.down = function (next) {
  next()
}

But it does not work and lists my return as undefined...Can any guide me for example how can I create a shared DB object and use it in another js file...

sp@sp-HP-ProBook-4530s:~/Documents/express$ migrate
  up : 1648736072728-posts.js
MyDB=undefined
  migration : complete

Thanks in advance


https://www.npmjs.com/package/migrate[migrate package link]

What I have tried:

I created an example but it does not work...
javascript - How to properly reuse connection to Mongodb across NodeJs application and modules - Stack Overflow[^]
Posted
Updated 25-Apr-22 0:08am
v2
Comments
stackprogramer 2-May-22 6:18am    
Anyone has not any offer?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900