javascript - 尝试使用 Mongoose 时出现 MongoClient 未连接错误?
问题描述
作为我课程的一部分,我正在学习 mongodb,现在正在学习 Mongoose。我已经完全按照课程中的方式编写了代码,但是当尝试使用 node app.js 启动它时,我收到以下错误:
$ node app.js (node:25772)
UnhandledPromiseRejectionWarning: MongoNotConnectedError: MongoClient must be connected to perform this operation
at Object.getTopology (C:\Users\donal\OneDrive\Desktop\Udemy Web Development\FruitsProject\node_modules\mongoose\node_modules\mongodb\lib\utils.js:391:11) at Collection.insertOne (C:\Users\donal\OneDrive\Desktop\Udemy Web Development\FruitsProject\node_modules\mongoose\node_modules\mongodb\lib\collection.js:150:61) at NativeCollection.<computed> [as insertOne] (C:\Users\donal\OneDrive\Desktop\Udemy Web Development\FruitsProject\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:200:33) at NativeCollection.Collection.doQueue (C:\Users\donal\OneDrive\Desktop\Udemy Web Development\FruitsProject\node_modules\mongoose\lib\collection.js:135:23) at C:\Users\donal\OneDrive\Desktop\Udemy Web Development\FruitsProject\node_modules\mongoose\lib\collection.js:82:24 at processTicksAndRejections (internal/process/task_queues.js:77:11) (Use
node --trace-warnings ... to show where the warning was created) (node:25772) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag
--unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1) (node:25772) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
我在终端的单独选项卡中运行了 mongosh,我尝试了几次搜索来寻找类似的问题。非常欢迎任何帮助!
这是我的完整 app.js 代码:
mongoose.connect("mongodb://localhost:27017/fruitsDB");
const fruitSchema = new mongoose.Schema({
name: String,
rating: Number,
review: String
});
const Fruit = mongoose.model("Fruit", fruitSchema);
const fruit = new Fruit({
name: "Apple",
rating: 7,
review: "Pretty solid as a fruit"
});
fruit.save();
mongoose.connection.close();
const findDocuments = function(db, callback) {
const collection = db.collection('fruits');
collection.find({}).toArray(function(err, fruits) {
assert.equal(err, null);
console.log("Found the following records");
console.log(fruits)
callback(fruits);
});
}
解决方案
mongoose.connect
是异步的,因此您尝试在与数据库建立连接之前执行代码。
const connectToMongo = async() => {
await mongoose.connect("mongodb://localhost:27017/fruitsDB", {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
});
return mongoose;
};
您现在可以使用 async/await 或 .then() 等待连接建立
(async function () {
await connecToMongo();
const fruitSchema = new mongoose.Schema({
name: String,
rating: Number,
review: String
});
const Fruit = mongoose.model("Fruit", fruitSchema);
const fruit = new Fruit({
name: "Apple",
rating: 7,
review: "Pretty solid as a fruit"
});
fruit.save();
mongoose.connection.close();
const findDocuments = function (db, callback) {
const collection = db.collection('fruits');
collection.find({}).toArray(function (err, fruits) {
assert.equal(err, null);
console.log("Found the following records");
console.log(fruits)
callback(fruits);
});
}
})
推荐阅读
- docker - 如何将服务器和数据库作为一个图像推送到 docker 注册表?
- google-apps-script - UrlFetchapp 响应错误 {"success":false,"error":"org.json.simple.JSONArray 无法转换为 org.json.simple.JSONObject"}
- azure - 团体超龄索赔
- node.js - 刷新时:在将标头发送到客户端后无法设置标头
- sql-server - SQL Server 2017 Express 比标准版更快
- java - 尝试运行 FizzBuzz 时尝试输出“Fizz”时出错
- python - 在没有 math.ceil() 的情况下向上舍入数学计算?
- html - 如何修复页面响应?
- python-2.7 - 将数据从 sqlite 数据库导出到 csv
- sql - 如何使用 SQL 查询识别增加或减少趋势