Node.js中使用Mongoose连接MongoDB并获取数据遇阻求助
Mongoose连接MongoDB及图书数据查询问题解决
问题场景
在Node.js v18.17.1环境下使用Mongoose连接MongoDB数据库,操作图书数据时遇到两个问题:
- MongoDB驱动提示
useNewUrlParser选项已弃用 livres.find()操作出现缓冲超时错误,无法获取数据
用户代码
const express = require("express"); const morgan = require("morgan"); const server = express(); const routeur = require("./routeur"); const mongoose = require("mongoose"); // Connecting to the database mongoose.connect("mongodb://localhost/biblio", { useNewUrlParser: true, useUnifiedTopology: true }); // Defining the book schema const livreSchema = mongoose.Schema({ _id: mongoose.Schema.Types.ObjectId, nom: String, auteur: String, pages: Number }); const livreModel = mongoose.model("Livre", livreSchema); // Attempting to fetch data from the database livreModel.find() .exec() .then(livres => { console.log(livres); }) .catch(); server.use(morgan("dev")); server.use(express.static("public")); server.use("/", routeur); server.listen(4000);
错误信息
(node:6876) [MONGODB DRIVER] Warning: useNewUrlParser is a deprecated option... (MongooseError: Operation livres.find() buffering timed out after 10000ms...)
解决方案
1. 移除已弃用的连接选项
在Node.js v18对应的Mongoose版本中,useNewUrlParser和useUnifiedTopology已经是默认启用的配置,无需手动声明,直接移除这两个参数即可消除弃用警告。同时建议添加数据库连接的状态监听,方便排查连接问题。
2. 等待数据库连接成功后执行查询
原代码中在连接尚未建立完成时就执行了find()操作,导致Mongoose的操作缓冲超时。需要将查询逻辑放在连接成功的回调中,或者通过async/await等待连接完成。
修改后的完整代码
const express = require("express"); const morgan = require("morgan"); const server = express(); const routeur = require("./routeur"); const mongoose = require("mongoose"); // 连接数据库并监听状态 mongoose.connect("mongodb://localhost/biblio") .then(() => { console.log("数据库连接成功"); // 连接成功后执行数据查询 fetchLivres(); }) .catch(err => { console.error("数据库连接失败:", err); }); // 定义图书Schema和Model const livreSchema = mongoose.Schema({ _id: mongoose.Schema.Types.ObjectId, nom: String, auteur: String, pages: Number }); const livreModel = mongoose.model("Livre", livreSchema); // 封装查询函数 async function fetchLivres() { try { const livres = await livreModel.find().exec(); console.log("获取到的图书数据:", livres); } catch (err) { console.error("查询图书数据失败:", err); } } server.use(morgan("dev")); server.use(express.static("public")); server.use("/", routeur); server.listen(4000, () => { console.log("服务器运行在端口4000"); });
额外注意事项
- 确保本地MongoDB服务已经启动,默认端口27017正常监听
- 确认
biblio数据库已经存在,Mongoose也会自动创建数据库(需确保连接权限正常) - 若使用MongoDB Atlas等远程数据库,需替换连接字符串并配置IP白名单
内容的提问来源于stack exchange,提问作者Kalyxos
相关产品推荐
相关产品推荐

