1

My code I am doing exactly as in the video but each time this issue occurs please help! here is the link to the video: https://www.youtube.com/watch?v=ipkLgbtS0LU&list=PLsY8aWop1tAH2mtv7jSTt6zr5Sfpu1WrM&index=3

var express = require('express');
var bodyParser = require('body-parser')

var app = express();

app.use('/static', express.static(__dirname + '/static'));
app.set('view engine', 'ejs');

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json())

var MongoClient = require("mongodb").MongoClient
MongoClient.connect("mongodb://localhost:27017", {useNewUrlParser: true, useUnifiedTopology: true}, function(error, client){
    var blog = client.db("blog");
    console.log("DB connected");

    app.get('/', function(req, res){
        res.send("Hello world")
    });

    app.get("/admin/dashboard", function(req, res) {
        res.render("admin/dashboard");
    });

    app.get("/admin/posts", function(req, res) {
        res.render("admin/posts");
    });

    app.post("/do-post", function(req, res){
        blog.collection("posts").insertOne(req.body, function(error, document){
            res.send("Posted Successfully!")
        });
    });

    app.listen(3000, function() {
        console.log("Server Connected");
    })
}) ```

1 Answer 1

2

Try this:

var blog = client.collection("blog");
console.log("DB connected");

client.db does not exist

In fact your 'client' is your database so you should rename it to db like so:

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

MongoClient.connect('mongodb://localhost:27017/animals', function(err, db) {
  if (err) {
    throw err;
  }
  db.collection('mammals').find().toArray(function(err, result) {
    if (err) {
      throw err;
    }
    console.log(result);
  });
});

Source: https://expressjs.com/en/guide/database-integration.html#mongodb

Sign up to request clarification or add additional context in comments.

2 Comments

Now it says collection of undefined.(((
Try to console log the parameters in the callback function and see what it gives you back. Please post the result right here.

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.