Node.js – Cannot read property ‘collection’ of undefined MongoDB

mongodbnode.js

Im trying to perform a CRUD op using Node and MongoDB.

Im getting the below error.

TypeError: Cannot read property 'collection' of undefined

const express = require('express')
const bodyParser= require('body-parser')
const MongoClient = require('mongodb').MongoClient
const app = express()
app.use(bodyParser.urlencoded({extended: true}))

const url = 'mongodb://localhost:27017/testdb';

var db
MongoClient.connect(url, function(err, client) {
  if (err) return console.log(err)
  var db = client.db('testdb');

})

app.post('/quotes', (req, res) => {
    var collectionName = 'quotes';
    var collection = db.collection(collectionName);
    collection.save(req.body, (err, result) => {
    if (err) return console.log(err)

    console.log('saved to database')
    res.redirect('/')
  })
})

Error trace:

TypeError: Cannot read property 'collection' of undefined
at app.post (/var/www/html/Express/SimpleCrud/server.js:20:21)
at Layer.handle [as handle_request] (/var/www/html/Express/SimpleCrud/node_modules/express/lib/router/layer.js:95:5)
at next (/var/www/html/Express/SimpleCrud/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/var/www/html/Express/SimpleCrud/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/var/www/html/Express/SimpleCrud/node_modules/express/lib/router/layer.js:95:5)
at /var/www/html/Express/SimpleCrud/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/var/www/html/Express/SimpleCrud/node_modules/express/lib/router/index.js:335:12)
at next (/var/www/html/Express/SimpleCrud/node_modules/express/lib/router/index.js:275:10)
at /var/www/html/Express/SimpleCrud/node_modules/body-parser/lib/read.js:130:5
at invokeCallback (/var/www/html/Express/SimpleCrud/node_modules/raw-body/index.js:224:16)

Im using Mongodb 3.1

Best Answer

Hei there,

Try with: const url = 'mongodb://localhost:27017';

Update: According to mongodb package v3.x, the declaration of the DB is done separately and not as a part of the URL. More info here: https://www.npmjs.com/package/mongodb

Related Topic