MongoClient: 在尝试使用Mongoose时出现未连接错误

8 浏览
0 Comments

MongoClient: 在尝试使用Mongoose时出现未连接错误

作为课程的一部分,我正在学习MongoDB和现在的Mongoose。我已经按照课程中的示例编写了代码,但在尝试用node app.js启动时,我收到以下错误:

node app.js

输出:

(node:25772) 未处理的Promise拒绝警告:MongoNotConnectedError:必须连接MongoClient才能执行此操作。

在Object.getTopology(C:\ Users \ donal \ OneDrive \ Desktop \ Udemy Web Development \ FruitsProject \ node_modules \ mongoose \ node_modules \ mongodb \ lib \ utils.js:391:11)

在Collection.insertOne(C:\ Users \ donal \ OneDrive \ Desktop \ Udemy Web Development \ FruitsProject \ node_modules \ mongoose \ node_modules \ mongodb \ lib \ collection.js:150:61)

在NativeCollection. [as insertOne](C:\ Users \ donal \ OneDrive \ Desktop \ Udemy Web Development \ FruitsProject \ node_modules \ mongoose \ lib \ drivers \ node-mongodb-native \ collection.js:200:33)

在NativeCollection.Collection.doQueue(C:\ Users \ donal \ OneDrive \ Desktop \ Udemy Web Development \ FruitsProject \ node_modules \ mongoose \ lib \ collection.js:135:23)

在C:\ Users \ donal \ OneDrive \ Desktop \ Udemy Web Development \ FruitsProject \ node_modules \ mongoose \ lib \ collection.js:82:24

在processTicksAndRejections(internal / process / task_queues.js:77:11)

(使用`node --trace-warnings ...`显示警告创建的位置)

(node:25772) 未处理的Promise拒绝警告:未处理的promise拒绝。此错误可能是由于在没有catch块的异步函数内抛出,或者通过拒绝未使用.catch()处理的promise而起。要在未处理的promise拒绝时终止节点进程,请使用CLI标志`--unhandled-rejections = strict`(请参阅https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode)。 (拒绝ID:1)

(node:25772) [DEP0018] 警告:未处理的Promise拒绝已弃用。将来,未处理的promise拒绝将以非零退出代码终止Node.js进程。

我在终端中的一个单独选项卡中运行着mongosh,并尝试了几次搜索类似的问题。我该怎么解决这个问题?

这是我完整的app.js代码:

const mongoose = require("mongoose");
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);
  });
}

0