0

enter image description here

const express = require('express');
const app = express();
app.use(express.urlencoded({
    extended: true
}));
const MongoClient = require('mongodb').MongoClient;
app.set('view engine', 'ejs');

var db;

app.listen(8080, function () {
    console.log('listening on 8080');
});


app.get('/', function (req, response) {
    response.sendFile(__dirname + '/index.html');
});

app.get('/write', function (req, response) {
    response.sendFile(__dirname + '/write.html');
});


app.get('/list', function (req,response) {
    db.collection('post').find().toArray(function(err, results){
        console.log(results);
    });
    response.render('list.ejs');
});

i want to call my data from collection of mongodb database.

but i have a Typeerror "collection" undefined!

please help me!

enter image description here i tried googling and i want to show my data to browser!

  • Hi, can you please provide more details around the error. Things like the full error and which line causes it would help. Thanks – MkMan Mar 31 '22 at 01:53
  • First, you will need to connect to the database server using the `MongoClient.connect(...)` method`. Then, read from the database, e.g., `MongoClient.db('db_name).collection('colln_name).find(...''`. See https://www.mongodb.com/docs/drivers/node/current/ – prasad_ Mar 31 '22 at 02:01
  • @prasad_ Thank you very much ! after i connected mongodb url then it works! – 김민섭 Mar 31 '22 at 05:20

1 Answers1

0

Here you have imported the module but you haven't configured the database.

const MongoClient = require('mongodb').MongoClient;
var mongoclient = new MongoClient(new Server("localhost", 27017), {native_parser: true});
var db = mongoclient.db("COLLECTION_NAME");

For more information check here https://mongodb.github.io/node-mongodb-native/api-generated/mongoclient.html

Nishanth Duvva
  • 665
  • 8
  • 18