Mongo url shorter TypeError: db.collection is not a function

Mongo url shorter TypeError: db.collection is not a function
0

#1
var express = require('express');
var MongoClient = require('mongodb').MongoClient;
var path = require('path');

var app = express();

var urlDB = 'mongodb://localhost:27017/data';

//connect to db
MongoClient.connect(urlDB, function (err, db) {
  if (err) {
    console.log('Unable to connect to the mongoDB server. Error: ', err);
  } else {
    console.log('Connection established to ', urlDB);
  }
  var port = process.env.PORT || 3500;

  app.listen(port, function(){
    console.log("Listening on port: " + port);
  });

  app.get('/new/:url(*)', function (req, res) {
    var url = req.params.url;
    var id = Math.floor(Math.random() * 10000);
    var retObj = {  "original_url": url ,
                    "short_url": "https://little-url.herokuapp.com/" + id
                  };
    db.collection("data").insert(retObj, function(err, data) {
      if (err) {console.log("Insert db err: " + err);}
    });
    res.json(retObj);
  });
});

When I go to http://localhost:3500/new/wowz I just get “TypeError: db.collection is not a function”


#2

I could be wrong because I have not learned the backend js stuff yet, but you reference db.collection inside the app.get callback function, but it appears db only has scope in the MongoClient.connect callback function.


#3

Thanks, unfortunately that’s not the issue. Even if I try to put db.collection(“data”).insert({“my”:obj}); right after the if/else I still get the same error of “TypeError: db.collection is not a function”


#4

If you put console.log(db, typeof db) before the if/else statement, what does it show?


#5

Thanks for getting back to me, console.log(db, typeof db) shows
’object’


#6

what about just db in the console.log?


#7

MongoClient {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
s:
{ url: ‘mongodb://localhost:27017/data’,
options:
{ socketOptions: {},
read_preference_tags: null,
readPreference: [Object],
dbName: ‘data’,
servers: [Object],
server_options: [Object],
db_options: [Object],
rs_options: [Object],
mongos_options: [Object],
socketTimeoutMS: 360000,
connectTimeoutMS: 30000,
promiseLibrary: [Function: Promise] },
promiseLibrary: [Function: Promise],
dbCache: {},
sessions: [] },
topology:
Server {
domain: null,
_events:
{ serverOpening: [Function],
serverDescriptionChanged: [Function],
serverHeartbeatStarted: [Function],
serverHeartbeatSucceeded: [Function],
serverHeartbeatFailed: [Function],
serverClosed: [Function],
topologyOpening: [Function],
topologyClosed: [Function],
topologyDescriptionChanged: [Function],
joined: [Function],
left: [Function],
ping: [Function],
ha: [Function],
authenticated: [Function],
error: [Function],
timeout: [Function],
close: [Function],
parseError: [Function],
open: [Object],
fullsetup: [Object],
all: [Object],
reconnect: [Function] },
_eventsCount: 22,
_maxListeners: undefined,
clientInfo:
{ driver: [Object],
os: [Object],
platform: ‘Node.js v6.10.3, LE’ },
s:
{ coreTopology: [Object],
sCapabilities: null,
clonedOptions: [Object],
reconnect: true,
emitError: true,
poolSize: 5,
storeOptions: [Object],
store: [Object],
host: ‘localhost’,
port: 27017,
options: [Object],
sessionPool: [Object],
promiseLibrary: [Function: Promise] } } }


#8

Well, I do not see a collection property for the db object, but I do not know enough about working with Mongo to tell you why.


#9

I fount the solution here https://stackoverflow.com/questions/47662220/db-collection-is-not-a-function-when-using-mongoclient-v3-0

Just use this for mongo 3.^

MongoClient.connect('mongodb://localhost:27017', (err, client) => {
  // Client returned
  var db = client.db('mytestingdb');
});