skip to Main Content

in connection.js


const mongoClient=require('mongodb').MongoClient
const state={
    db:null
}
module.exports.connect=function (done){
    const url='mongodb://localhost:27017/'
    const dbname='shopping'

   mongoClient.connect(url,(err,data)=>{
     if(err) return done(err)
       state.db=data.db(dbname)   
    })
   done()
}
module.exports.get=()=>state.db

in product-helpers

var db=require('../config/connection')

module.exports={

    addProduct:(product,callback)=>{
        console.log(product)
        db.get().collection('product').insertOne(product).then((data)=>{
            console.log(data);
            callback(true)
       })
            
        
        
    }
}

I am unable to find what’s the error. I am new to nodejs.

I tried to submit a form but not working. How can I fix this.

2

Answers


  1. In your connection.js file, you are calling the done() function before the database connection is established. You need to move the done() function inside the mongoClient.connect() callback to ensure that it is called only after the connection is successfully made.

    const state = {
        db: null
    };
    
    module.exports.connect = function (done) {
        const url = 'mongodb://localhost:27017/';
        const dbname = 'shopping';
    
        mongoClient.connect(url, (err, client) => {
            if (err) return done(err);
    
            state.db = client.db(dbname);
            done();
        });
    };
    
    module.exports.get = () => state.db;`
    
    Login or Signup to reply.
  2. You cannot use module.exports to export multiple parts( i.e function ,object ,properties) from the same module .You should use only exports keyword to export more than one properties from a single module.

    I have answered a same question here on this platform where I described in details how to create connection with database and get the DB-name using mongodb driver.

    You will also get a crystal clear idea about how to import the module to get the database instance in your others module.

    Please check the link below. I am sure you will get you answer there.

    Node.js Express application not logging MongoDB connection status

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search