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
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.
You cannot use
module.exports
to export multiple parts( i.e function ,object ,properties) from the same module .You should use onlyexports
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 theDB-name
usingmongodb
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