0

Ive been getting a type error with my collection function that was working previously.

This code was working previously in my other project. I just ended up recycling alot of the code and now ive been getting this error. My mongodb connection code is in another file and is connected.

  var expect = require('chai').expect;
  var MongoClient = require('mongodb').MongoClient;
  var ObjectId = require('mongodb').ObjectId;
  var mongo    = require('mongodb').MongoClient;
  var db       = require('mongodb').MongoClient;

module.exports = function (app ,db) {
    db.collection.insertOne({
    "title": req.body.title,
    "_id": Math.random
  }).touchEvent(doc =>
    res.status(200).json({
      "status":"success",
     "_id": req.body._id,
      "title": req.body.title
    })).catch(err => {throw err;});
  })
};

The exact error message is "TypeError: Cannot read property 'collection' of undefined". Any help would be appreciated :)

danh
  • 62,181
  • 10
  • 95
  • 136
Naval
  • 15
  • 4
  • Just to clarify, my db.collection command is the one that is triggering the error. – Naval Jul 23 '19 at 20:26
  • The error indicates that `db` is undefined. Which means `MongoClient` and `mongo` are undefined, too. See https://codereview.stackexchange.com/a/69660 – danh Jul 23 '19 at 20:37

2 Answers2

0

In your case db in the line db.collection.insertOne( is whatever is passed into the function, not the db defined earlier in the file. This might be confusing since both variables are named db, but in fact they are two different things.

For more info on JavaScript scopes see: What is the scope of variables in JavaScript?

tantalum
  • 2,354
  • 1
  • 15
  • 22
  • Your comment was helpful however, I removed the db variable from the export function and I was still getting the same error. Thank you for your input – Naval Jul 23 '19 at 20:52
0

Try this: Make db variable global and call it inside function like this

global.db       = require('mongodb').MongoClient;
module.exports = function (app) {
    db.collection.insertOne({
       "title": req.body.title,
        "_id": Math.random
     }).touchEvent(doc => res.status(200).json({
      "status":"success",
     "_id": req.body._id,
      "title": req.body.title
    })).catch(err => {throw err;});
  })
};

Check here

I hope it helps.

Nicholas Mberev
  • 1,563
  • 1
  • 14
  • 14