mongo db node.js some error with 'db' being undefined
I am following a YouTube video https://www.youtube.com/watch?v=kwPWwczwi6c&list=PLsY8aWop1tAHigCqvxZ61XK3a8I509VRx&index=2 after creating a server.js file and running nodemon server.js file entered below
var express = require("express");
var app = express();
var formidable = require("express-formidable");
app.use(formidable());
var mongodb = require("mongodb");
var mongoClient = mongodb.MongoClient;
var ObjectId = mongodb.ObjectId;
var http = require("http").createServer(app);
var bcrypt = require("bcrypt");
var fileSystem = require("fs");
var jwt = require("jsonwebtoken");
var accessTokenSecret = "myAccessTokenSecret1";
app.use("/public", express.static(__dirname + "/public"));
app.set("view engine", "ejs");
var socketIO = require("socket.io")(http);
var socketID = "";
var users = [];
var mainURL = "http://localhost:3000";
socketIO.on("connection", function (socket) {
console.log("User connected", socket.id);
socketID = socket.id;
});
http.listen(3000, function () {
console.log("Server started.");
mongoClient.connect("mongodb://localhost:27017", function (error, client) {
var database = client.db("Social_De_Test");
console.log("Database connected.");
app.get("/signup", function (request, result) {
result.render("signup");
});
});
});
I get an error
[nodemon] 2.0.4
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node server.js`
Server started.
(node:5776) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the
MongoClient constructor.
(Use `node --trace-deprecation ...` to show where the warning was created)
F:\Project\Workspace\heroku\node_modules\mongodb\lib\utils.js:668
throw error;
^
TypeError: Cannot read property 'db' of undefined
at F:\Project\Workspace\heroku\server.js:35:27
at F:\Project\Workspace\heroku\node_modules\mongodb\lib\utils.js:665:9
at F:\Project\Workspace\heroku\node_modules\mongodb\lib\mongo_client.js:224:23
at connectCallback (F:\Project\Workspace\heroku\node_modules\mongodb\lib\operations\connect.js:366:5)
at F:\Project\Workspace\heroku\node_modules\mongodb\lib\operations\connect.js:433:14
at Server.<anonymous> (F:\Project\Workspace\heroku\node_modules\mongodb\lib\topologies\server.js:230:11)
at Object.onceWrapper (events.js:421:26)
at Server.emit (events.js:314:20)
at Pool.<anonymous> (F:\Project\Workspace\heroku\node_modules\mongodb\lib\core\topologies\server.js:436:21)
at Pool.emit (events.js:314:20)
[nodemon] app crashed - waiting for file changes before starting...
Solution 1:
Seems like this line:
var database = client.db("Social_De_Test");
Should replace client to mongoClient:
var database = mongoClient.db("Social_De_Test");