Jan Tuđan
Jan Tuđan

Reputation: 171

Cannot read collection from MongoDB

So, I'm trying to connect a mongo database and it's already connected. But my issue is that I can't read collection from mongo in another file, it says: db.collection is not a function.

So this is my db.js file:

const { MongoClient } = require('mongodb');

let connection_string = 'mongodb+srv://username:[email protected]/myFirstDatabase?retryWrites=true&w=majority';

let client = new MongoClient(connection_string, {
    useNewUrlParser: true,
    useUnifiedTopology: true
});

let db = null

export default () => {
    
    return new Promise((resolve, reject) =>{
        
        if (db && client.isConnected()){
            resolve(db)
        }
        client.connect(err => {
            if(err){
                reject("Error in connection " + err)
            }
            else{
                console.log("Success")
                db = client.db("posts")
                resolve(db)
                coll = db.collection('posts');
            }
        });
    })
}; 

The thing is I got successfully connected to a database, but when I try to work with collections it says they are not functions.

This is my second file where I already imported connect from db.js, so here is what I want to do:

app.post('/posts', async (req,res)=>{
    let db = connect();
    
    let posts = req.body;
    
    let result = await db.collection('posts').insertOne(posts);
})

Here is the exact error I'm getting:

UnhandledPromiseRejectionWarning: TypeError: db.collection is not a function
at _callee$ (C:\Users\Jan\Desktop\Webshop\posts\src\/index.js:21:33)
at tryCatch (C:\Users\Jan\Desktop\Webshop\posts\node_modules\regenerator-runtime\runtime.js:63:40)
at Generator.invoke [as _invoke] (C:\Users\Jan\Desktop\Webshop\posts\node_modules\regenerator-runtime\runtime.js:294:22)
at Generator.next (C:\Users\Jan\Desktop\Webshop\posts\node_modules\regenerator-runtime\runtime.js:119:21)
at asyncGeneratorStep (C:\Users\Jan\Desktop\Webshop\posts\src\index.js:11:103)
at _next (C:\Users\Jan\Desktop\Webshop\posts\src\index.js:13:194)
at C:\Users\Jan\Desktop\Webshop\posts\src\index.js:13:364
at new Promise (<anonymous>)
at C:\Users\Jan\Desktop\Webshop\posts\src\index.js:13:97
at C:\Users\Jan\Desktop\Webshop\posts\src\/index.js:16:1

Upvotes: 0

Views: 115

Answers (0)

Related Questions