运行Node.js连接MongoDB无响应,如何本地部署MongoDB并插入数据?
问题排查与解决步骤
一、修复代码无响应问题
你的代码里collection.insertMany()是异步操作,但未添加await,导致函数提前返回并关闭数据库连接,插入操作未完成就被中断,最终出现无响应情况。修改后的代码如下:
const { MongoClient } = require('mongodb'); // Connection URL const url = 'mongodb://127.0.0.1:27017'; const client = new MongoClient(url); // Database Name const dbName = 'fruitsDB'; async function main() { // 连接MongoDB服务器 await client.connect(); console.log('Connected successfully to server'); const db = client.db(dbName); const collection = db.collection('fruits'); // 等待插入操作完成 await collection.insertMany([ { name: "Apple", score: 8, review: "Great fruit" }, { name: "Orange", score: 6, review: "Kinda sour" } ]); return 'done.'; } main() .then(console.log) .catch(console.error) .finally(() => client.close());
二、本地启动MongoDB服务器
1. 确认MongoDB已安装
先确保你已在本地完成MongoDB的安装(根据操作系统选择对应版本)。
2. 启动服务
Windows系统:
打开命令提示符,执行:mongod若提示命令不存在,需将MongoDB安装目录下的
bin文件夹添加到系统环境变量,或直接进入该bin目录执行命令。macOS/Linux系统:
打开终端,执行:mongod若通过Homebrew安装,也可使用:
brew services start mongodb-community启动成功后,终端会显示
waiting for connections on port 27017的提示,说明本地MongoDB服务已正常运行。
三、重新运行程序
保持MongoDB服务的终端窗口处于打开状态,回到Hyper终端的FruitsProject目录下,执行:
node app.js
正常情况下会输出:
Connected successfully to server done.
表示数据已成功插入到fruitsDB数据库的fruits集合中。
四、验证插入结果
打开新终端窗口,通过MongoDB Shell查看数据:
mongo
进入Shell后依次执行:
use fruitsDB db.fruits.find()
即可看到你插入的两条水果数据。
内容的提问来源于stack exchange,提问作者MakT
相关产品推荐
相关产品推荐

