0

I'm trying to connect nodejs to mongodb database but lots of errors occur

 let express = require ('express')

 let mongodb = require ('mongodb')

 let app = express()
 let db 

 let connectionString = 
'mongodb+srv://Akshay:[email protected]/TodoApp? 
 retryWrites=true&w=majority'
 mongodb.connect(connectionString, {useNewUrlParser: true, useUnifiedTopology: true}, function 
 (err, client){

 db = client.db()
 app.listen(3000)
})

My controller:

 app.post('/create-item', function(req, res) {
  db.collection('item').insertOne({text: req.body.item}, function() {
  res.send("Thanks for submitting the form.")
  })

Error message:

'db' is not defined

2 Answers 2

1

I think you have problem with your file structure. Probably you are not including db to your controller.

Please, create a new file and call it database.js

Design your database.js like this:

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

class DatabaseSingleton {

    constructor() {
        const uri = process.env.DB_CONNECTION_STRING;
        
        this.client = new MongoClient(uri, { useUnifiedTopology: true });
        this.isConnected = false;

        this.client.connect().then(()=>{this.isConnected = true});
    }

    /**
     * Returns the promise of a Database object. (It waits until a connection to the database was successful)
     * @returns {Promise<any>}
     */
    get mongo() {
        return new Promise(async (resolve, reject) => {
            let timedOut = false;
            setTimeout(()=>{timedOut = true}, 300 * 1000);
            while (!this.isConnected && !timedOut){
                await new Promise((resolve)=>{setTimeout(()=>{resolve()}, 100)}) // Snooze the thread for 100ms without blocking the event loop
            }

            if (timedOut){
                reject(false);
            } else {
                resolve(this.client.db());
            }
        })
    }
}

// *** Setting up singleton ***
const SINGLETON_KEY = Symbol.for("MyProject.MyDB");

var globalSymbols = Object.getOwnPropertySymbols(global);
var hasInstance = (globalSymbols.indexOf(SINGLETON_KEY) > -1);

// If there is no instance of the singleton, make the instance.
if (!hasInstance){
    global[SINGLETON_KEY] = new DatabaseSingleton()
}

// Define a function to retrieve a singleton instance
var singleton = {};
Object.defineProperty(singleton, "instance", {
    get: function(){
        return global[SINGLETON_KEY];
    }
});

// The singleton should never be changed
Object.freeze(singleton);

module.exports = singleton;

// *** End of singleton setup ***

And convert your controller something like:

const database = require('./database').instance;

 
 app.post('/create-item', function(req, res) {
  const db = await database.mongo; // Call db here
  db.collection('item').insertOne({text: req.body.item}, function() {
  res.send("Thanks for submitting the form.")
  })
Sign up to request clarification or add additional context in comments.

Comments

0

Try this. Create a db.js file to setup database connection only and export the client.

    const dotenv = require("dotenv");
dotenv.config();
const mongodb = require("mongodb");
mongodb.connect(
    process.env.CONNECTIONSTRING,
    {
        useNewUrlParser: true,
        useUnifiedTopology: true,
    },
    (err, client) => {
        module.exports = client
        const server = require("./server");
        server.listen(process.env.PORT);
    }
);

Now in your server.js file require the client that are exported.

const client = require('./client')

now use this as

client.db('databaseName').collection('item').insertOne({})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.