简体   繁体   English

无法连接到 mongo 数据库

[英]cannot connect to the mongo database

I cann't connect to the database mongo db.我无法连接到数据库 mongo db。 The type error is present.存在类型错误。 How can I do?我能怎么做? server.js:服务器.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.您只需要在连接字符串中使用mongodb://localhost:27017/即可解决该错误。 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');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM