Type Error: Cannot read property 'collection' of null

Viewed 32

Here is my code

//--conection.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=function(){
    return state.db
}

//--helpers.js--//

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(data.insertdld)

        })
    }
}

This is the code I have written, please help me to find the solution and it is is showing this error "Cannot read property 'collection' of null"..

1 Answers

Your mongo instance is null. This way worked for me

async function main(){
    const uri = "mongodb://localhost:27017/shopping";
 

    const client = new MongoClient(uri);
 
    try {
        await client.connect();
 
        await  listDatabases(client);
       
    } catch (e) {
        console.error(e);
    } finally {
        await client.close();
    }
}

main().catch(console.error);
Related