How can I export the mongo database handler to Node.js?

I am new to Node and Mongo, I tried to connect to the mongo database in one file and export the database handler to many other files, so I do not need to connect to the database in all the files that you need to connect to it. This is how I tried to do it

// db.js
var client = require('mongodb').MongoClient
var assert = require('assert')
var url = 'mongodb://localhost:27017/test'

client.connect(url, (err, db) => {
  assert.equal(err, null)
  module.exports = db
})

After exporting the db handler, I tried to access them in another file as follows

var db = require('./db')
console.log(db.collection('col'))

but it raises a TypeError, saying it is db.collectionnot a function. How can I access db handler methods in other files?

+4
source share
3 answers

, callback1. , 1 2 async.

db.js

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
let callback, db;
// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
  assert.equal(null, err);
  console.log("Connected successfully to server");

  db = client.db(dbName);
  callback(db)

  client.close();
});

module.exports = function(cb){
  if(typeof db != 'undefined' ){
    cb(db)
  }else{
    callback = cb
  }
}

other.js

const mongo = require("./db");
mongo((db) => {
     //here get db handler
})
+1

. . .

 const MongoClient = require('mongodb').MongoClient;

 let collections = {}

   MongoClient.connect(url, function(e, client) {
    if(e) {
      console.log(e)
      throw {error:'Database connection failed'}
     }

     let db = client.db('example-db');
     collections.users = db.collection('users')
   });

   module.exports = collections

  const collections  = require('../db/mongo')
  collections.users.findOne({userName:'userName'})

, , db. , db .

   module.exports = {
       db:db,
       collections:collections
    }
+1

, init() , , db. , db, , , , .

0

Source: https://habr.com/ru/post/1609735/


All Articles