我无法连接到数据库mongo db。存在类型错误。我能怎么做? 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
});
控制台日志:
API app started
TypeError: Cannot read property 'collection' of undefined
at /home/bukrole/db.project/server.js:18:6
答案 0 :(得分:1)
您只需要在连接字符串中使用mongodb://localhost:27017/
即可解决该错误。但是,您需要单独提及数据库名称作为选项。
var db;
MongoClient.connect("mongodb://localhost:27017", { useUnifiedTopology: true }, (err, client) => {
db = client.db('test_db');
});