Eugene
Eugene

Reputation: 65

NodeJS TypeError: db.collection is not a function

Server error while connecting to mongoDB

TypeError: db.collection is not a function

at /Users/prokhorov/Desktop/IOS DEV /Shop/Shop/server.js:9:8
at Layer.handle [as handle_request] (/Users/prokhorov/Desktop/IOS DEV /Shop/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/prokhorov/Desktop/IOS DEV /Shop/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/Users/prokhorov/Desktop/IOS DEV /Shop/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/prokhorov/Desktop/IOS DEV /Shop/node_modules/express/lib/router/layer.js:95:5)
at /Users/prokhorov/Desktop/IOS DEV /Shop/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/Users/prokhorov/Desktop/IOS DEV /Shop/node_modules/express/lib/router/index.js:335:12)
at next (/Users/prokhorov/Desktop/IOS DEV /Shop/node_modules/express/lib/router/index.js:275:10)
at expressInit (/Users/prokhorov/Desktop/IOS DEV /Shop/node_modules/express/lib/middleware/init.js:40:5)
at Layer.handle [as handle_request] (/Users/prokhorov/Desktop/IOS DEV /Shop/node_modules/express/lib/router/layer.js:95:5)

The first time I came across the need to use Node.js. Hope you can help. thanks This is the code for my server.js file

var MongoClient = require('mongodb').MongoClient;

var app = express();
var db;

app.get('/', function(req, res) {
    db.collection('product').find().toArray(function (err, docs) {
        if (err) {
            console.log(err);
            return res.sendStatus(500);
        }
        res.send(docs);
    })
})

MongoClient.connect('mongodb+srv://test:[email protected]/myFirstDatabase?retryWrites=true&w=majority', function (err, database) {
    if (err) {
        return console.log(err);
    }
    db = database;
    app.listen(3012, function () {
        console.log('API app started');
    })
})

Upvotes: 0

Views: 621

Answers (1)

Sakil Khan
Sakil Khan

Reputation: 140

you can try this I think this should work. I try it locally here is the sample code

const express = require('express');
const app = express();
let MongoClient = require('mongodb').MongoClient;
var db;

MongoClient.connect('mongodb://localhost:27017', function (err, client) {
  if (err) throw err;
  db = client.db('DatabaseName');
  app.listen(3000);
});

app.get('/', (req, res) => {
  db.collection('CollectionName')
    .find()
    .toArray(function (err, result) {
      if (err) throw err;
      res.send(result);
    });
});

Upvotes: 1

Related Questions