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

toiithl6  于 12个月前  发布在  Go
关注(0)|答案(2)|浏览(146)

作为我课程的一部分,我正在学习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 代码:

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);

  });
}
xbp102n0

xbp102n01#

我遇到了同样的问题,罪魁祸首是在JavaScript代码体中调用mongoose.connection.close();。正如AnanthDev提到的,mongoose是异步的,在它能够执行操作之前就关闭了连接。
下面的工作原理是因为mongoose.connection.close()是在一个回调函数中,并且在操作执行之后才运行。

Fruit.insertMany([kiwi, orange, banana], function(err) {
    if (err) {
        console.log(err);
    } else {
        mongoose.connection.close();
        console.log("Successfully saved all the fruits to fruitsDB");
    }
})
wtzytmuj

wtzytmuj2#

mongoose.connect是xdc,所以您尝试在与数据库建立连接之前执行代码。

const connectToMongo = async() => {
    await mongoose.connect("mongodb://localhost:27017/fruitsDB", {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        useFindAndModify: false,
    });
    return mongoose;
};

现在,您可以使用. wait/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);

        });
    }
})

相关问题