连接到本地 mongodb 后停止"/>
node.js 在连接到本地 mongodb 后停止
我正在尝试连接到我在 mongodb 上的数据库并从中获取一些数据。但是在建立连接后,终端停止运行,我必须按 ctrl+C。
这是我的代码
const express = require('express');
const mongoose = require('mongoose');
const app = express();
const port = 3000;
const dbName = 'inventory';
const dbUrl = `mongodb://localhost:27017/${dbName}`;
// Define the schema and model for the "cars" collection
const carSchema = new mongoose.Schema({
make: String,
model: String,
year: Number
});
const Car = mongoose.model('Car', carSchema);
// Connect to the MongoDB server
mongoose.connect(dbUrl, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => {
console.log(`Connected to database '${dbName}'`);
// Define a GET route handler that fetches all cars from the database
app.get('/cars', async (req, res) => {
try {
const cars = await Car.find();
console.log(cars); // Log the fetched cars to the console
res.json(cars);
} catch (err) {
console.error(err);
res.status(500).send('Server error');
}
});
// Start the Express app
app.listen(port, () => {
console.log(`Server is listening on port ${port}`);
});
})
.catch((err) => {
console.error(err);
});
我知道我已经建立了连接,因为我在我的控制台中得到了这个
{"t":{"$date":"2023-05-13T21:12:56.152-06:00"},"s":"I", "c":"NETWORK", "id":51800, "ctx":"conn29","msg":"client metadata","attr":{"remote":"127.0.0.1:53075","client":"conn29","doc":{"driver":{"name":"nodejs|Mongoose","version":"5.3.0|7.1.1"},"platform":"Node.js v16.17.1, LE","os":{"name":"win32","architecture":"x64","version":"10.0.19045","type":"Windows_NT"}}}}
{"t":{"$date":"2023-05-13T21:13:06.654-06:00"},"s":"I", "c":"NETWORK", "id":22943, "ctx":"listener","msg":"Connection accepted","attr":{"remote":"127.0.0.1:53096","uuid":"9611eab4-7a75-49a0-9b44-d644599fe37c","connectionId":30,"connectionCount":18}}
{"t":{"$date":"2023-05-13T21:13:06.656-06:00"},"s":"I", "c":"NETWORK", "id":51800, "ctx":"conn30","msg":"client metadata","attr":{"remote":"127.0.0.1:53096","client":"conn30","doc":{"driver":{"name":"nodejs|Mongoose","version":"5.3.0|7.1.1"},"platform":"Node.js v16.17.1, LE","os":{"name":"win32","architecture":"x64","version":"10.0.19045","type":"Windows_NT"}}}}
我也进入我的控制台日志
Connected to database 'inventory'
Server is listening on port 3000
我觉得问题出在我的机器上,因为我不知道还能尝试什么。 我之前遇到一个问题,我的 python 应用程序可以连接到我的 mongodb,但我的 node.js 应用程序不能。
回答如下:你的代码对我来说似乎是正确的,所以我只能提供这些建议:
我做了一些容器的事情,通常防火墙会导致数据库连接出现问题。确保在您的机器和数据库上配置了这些。
此外,检查您是否有权从
inventory
数据库中读取。
另一个故障排除步骤是查看
cars
集合是否确实存在。
您还可以在您的应用程序上尝试调试器,看看它究竟卡在哪里。也许问题出在您的代码中。
更多推荐
node.js 在连接到本地 mongodb 后停止
发布评论