skip to Main Content

indexHelpers.js

var db = require("../config/connection");
var collections = require("../config/collections");
var ObjectId = require("mongodb").ObjectId;

module.exports = {
  addPerson: (personDetails) => {
    return new Promise((resolve, reject) => {
     db.get().collection(collections.USER_DETAILS)
        .insertOne(personDetails)
        .then((details) => {
          resolve(details);
        });
    });
  },
};
 

In the indexhelpers.js the db.get() function return null… so when I try to call db.get().collection() it returns the error TypeError: Cannot read properties of null (reading ‘collection’)

So this is my connection .js.I couldn’t find out why i get this error

connection.js

const mongoClient = require("mongodb").MongoClient;
const state = {
  db: null,
};
module.exports.connect = function (done) {
  const url = "mongodb://localhost://27017";
  const dbname = "CMS";
  mongoClient.connect(url, { useUnifiedTopology: true }, (err, data) => {
    if (err) return done(err);
    state.db = data.db(dbname);
  });

  done();
};

module.exports.get = function () {
  return state.db;
};

app.js

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var db = require("./config/connection");

var indexRouter = require('./routes/index');
var hbs = require("express-handlebars");
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
//handlebars as the template engine
app.engine(
  "hbs",
  hbs.engine({
    extname: "hbs",
    defaultLayout: "layout",
    layoutsDir: __dirname + "/views/"
  })
);

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
db.connect((err) => {
  if (err) console.log("connection error" + err);
  else console.log("--------Database Connected--------");
});

app.use('/', indexRouter);


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

I tried console.log(db.get()) which returns null. actually db.get() must return some values but I am not getting0 it

2

Answers


  1. Chosen as BEST ANSWER

    Ok i got it i downgraded my mongodb packkage version to 4.5.0. I think newer package has some problems with my code .

    Hope it helps !!!


  2. As you are using your local server mongodb 27017, please check properly is it working or not firstly. Alternatively create free account in mongodb atlas then use those MongoDB URI instead of local url.

    My suggestion is to use mongoose package instead of mongodb client.

    Thanks

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search