I cann't connect to the database mongo db. The type error is present. How can I do? server.js:
let MongoClient = require("mongodb").MongoClient;
let express = require("express");
let bodyParser = require("body-parser");
let app = express();
let db;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/", function(req, res) {
res.send("Hello API");
});
app.listen(3114, function() {
console.log("API app started");
});
MongoClient.connect("mongodb://localhost:27017/test_db", {
useUnifiedTopology: true,
useNewUrlParser: true
});
Console log:
API app started
TypeError: Cannot read property 'collection' of undefined
at /home/bukrole/db.project/server.js:18:6
You just need to use mongodb://localhost:27017/
in your connection string to resolve that error. However, you need to mention the db name separately as an option.
var db;
MongoClient.connect("mongodb://localhost:27017", { useUnifiedTopology: true }, (err, client) => {
db = client.db('test_db');
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.