0

TypeError: Cannot read property 'then' of undefined Can you help me fix this? Thank you.

var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var mongodb = require('mongodb'); 

var dbConn = mongodb.MongoClient.connect('mongodb://localhost:27017', 
function(err, db) {
    if(err){
        throw err;
    }else{
        console.log("connected");
    }
})

var app = express();

app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.resolve(__dirname, './')));

app.post('/post-feedback', function (req, res) {
    dbConn.then(function(db) {
        delete req.body._id; // for safety reasons
        db.collection('feedbacks').insertOne(req.body);
    });    
        res.send('Data received:\n' + JSON.stringify(req.body));
    });

app.get('/view-feedbacks',  function(req, res) {
        dbConn.then(function(db) {
        db.collection('feedbacks').find({}).toArray().then(function(feedbacks) {
            res.status(200).json(feedbacks);
        });
    });
});

app.listen(process.env.PORT || 3000, process.env.IP || '0.0.0.0' );

TypeError: Cannot read property 'then' of undefined Can you help me fix this? Thank you.

C.E James
  • 315
  • 1
  • 5
  • 22

3 Answers3

2

The following approach should get you started but should not use this for production
(Reference: How do I manage MongoDB connections in a Node.js web application?). Read through for another production starters.

var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var mongodb = require('mongodb'); 

var dbConn = function() {
    return new Promise((resolve, reject) => {
        mongodb.MongoClient.connect('mongodb://localhost:27017', 
            function(err, db) {
                if(err){
                    return reject(err);
                }else{
                    return resolve(db);
                } 
        });
    });
}

var app = express();

app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.resolve(__dirname, './')));

app.post('/post-feedback', function (req, res) {
    dbConn()
    .then(function(db) {
        delete req.body._id; // for safety reasons
        db.collection('feedbacks').insertOne(req.body);
        res.send('Data received:\n' + JSON.stringify(req.body));
    })
    .catch(err => {
        console.log(err)
        res.send('Error');
    })
});

app.get('/view-feedbacks',  function(req, res) {
        dbConn()
        .then(function(db) {
            db.collection('feedbacks').find({}).toArray().then(function(feedbacks) {
                res.status(200).json(feedbacks);
            });
        })
        .catch(err => {
            console.log(err);
            res.status(500).json({});
        });
});

app.listen(process.env.PORT || 3000, process.env.IP || '0.0.0.0' );


Production Starter:

Ideally you will have something like following say in a file db.js

let mongoClient = require('mongodb').MongoClient,
   logger = require('winston');

function DATABASE() {
   this.dbObj = null;
   this.myCollection = null; // You will need to add more collections here
}

DATABASE.prototype.init = function (config, options) {
   let self = this;
   self.config = config; //can pass a config for different things like port, ip etc.
   self.logger = logger;

   return new Promise(function (resolve, reject) {
      if (self.initialized) {
         return resolve(self);
      }
      let connectionUri = "mongodb://localhost:27017";     //self.config.mongo.connectionUri;
      mongoClient.connect(connectionUri, {native_parser: true}, function     (err, db) {
         if (err) {
            reject(err);
         }
         else {
            self.dbObj = db;
            self.myCollection = db.collection('myCollection');
            self.initialized = true;
            self.logger.info("db init success");
            return resolve(self);
         }
      });
   });
};

var dbObj = null;

var getdbObj = function () {
   if (!dbObj) {
      dbObj = new DATABASE();
   }
   return dbObj;
}();

module.exports = getdbObj;


In your main app start file you will have something like:

let dbObj = require('./db.js');
dbObj.init()
.then(db => {
     console.log('db initialized successfully');
     //db.dbObj.collection('myCollection').find()
     //or
     //db.myCollection.find() because this has been already initialized in db.js
     var app = express();
     app.use(bodyParser.urlencoded({ extended: false }));
     app.use(express.static(path.resolve(__dirname, './')));

     app.post('/post-feedback', function (req, res) {
         delete req.body._id; // for safety reasons
         db.dbObj.collection('feedbacks').insertOne(req.body);
         res.send('Data received:\n' + JSON.stringify(req.body));
     });

     app.get('/view-feedbacks',  function(req, res) { 
         //db.collection('feedbacks')
     });

     app.listen(process.env.PORT || 3000, process.env.IP || '0.0.0.0' )
})
.catch(err => console.log(err));
amangpt777
  • 525
  • 5
  • 10
0

Try this, dbConn is not promise

app.post('/post-feedback', function (req, res) {
    mongoose.connection.db.collection('feedbacks', function (err, collection) {
        collection.insertOne(req.body);
        res.send('Data received:\n' + JSON.stringify(req.body));
    });

    // OR

    const Model = mongoose.model('feedbacks');
    let model = new Model();
    model = Object.assign(model, req.body);
    model.save().then((result) => {
        res.send('Data received:\n' + JSON.stringify(req.body));
    });
});
Rahul Sharma
  • 9,534
  • 1
  • 15
  • 37
0

Its working .
If you are getting any TypeError (UnhandledPromiseRejectionWarning: TypeError: db.collection is not a function) form mongodb. Just change the version of mongodb to -

"mongodb": "^2.2.33"

"use strict"
var express = require('express');
var mongodb = require('mongodb');
var app = express();
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/feedback';
// no need to call then() yet
var dbConn = MongoClient.connect(url);

app.set('port', 5000);

app.listen(app.get('port'), function() {
    console.log('feedback is running on port', app.get('port'));
});


app.get('/view-feedback', function(req, res, next) {
    // the connection is opened

    dbConn.then(function(db) {
        // var dbo = db.db("feedback");
        db.collection('feedback').find({}).toArray().then(function(docs) {
            // return docs;
            res.json(docs)
        });
    });
});
Arpit Yadav
  • 516
  • 8
  • 21