TypeError: Cannot destructure property `db` of 'undefined' or 'null'

Demesew Abebe picture Demesew Abebe · Apr 19, 2018 · Viewed 40.5k times · Source

I am getting a TypeError in my variable assignment for mongodb connection. Is there a workaround for this?

//server.js
var mongoose = require('mongoose');
var config = require('./config');

var { db: {user,pass,host,port,name } } = config;

var connectionString = `mongodb://${user}:${pass}@${host}:${port}/${name}`;

mongoose.connect(connectionString, { useMongoClient: true });

Error

C:\mean\webguidv1\server.js:65
  db: {
  ^

TypeError: Cannot destructure property `db` of 'undefined' or 'null'.

Here is my config.js file

// config.js
var env = process.env.NODE_ENV; // 'dev' or 'test'

var dev = { app: { port: 3000 }, db: {user: '', pass: '', host: '', port: , name: '' }};

var test = { app: { port: 3000 }, db: {user: '', pass: '', host: '', port: , name: '' }};

var config = { dev, test };

module.exports = config[env];

Answer

Kevin Ghadyani picture Kevin Ghadyani · Jul 29, 2018

You're trying to deconstruct config where config is undefined or null. In this case, I'm thinking it's undefined.

If you console.log(require('./config')), you'll probably get undefined.

This error also appears if you try to deconstruct an object in function args in Node 10.7.0.