0

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');
    })
})
1

1 Answer 1

1

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);
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

if there is any query or confusion let me know. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.