mongodb 错误MongoNotConnectedError:客户端必须在运行操作之前连接-如何摆脱错误?

ulmd4ohb  于 2023-03-29  发布在  Go
关注(0)|答案(2)|浏览(775)

我正在创建一个项目,我使用一个种子文件来为我的数据库添加测试数据。
当我在node.js中运行这个文件时,我得到的错误如下:

Database connected
D:\OUWork\Year 6\TM470\Project\node_modules\mongodb\lib\operations\execute_operation.js:24
            throw new error_1.MongoNotConnectedError('Client must be connected before running operations');
                  ^

MongoNotConnectedError: Client must be connected before running operations
    at executeOperationAsync (D:\OUWork\Year 6\TM470\Project\node_modules\mongodb\lib\operations\execute_operation.js:24:19)
    at D:\OUWork\Year 6\TM470\Project\node_modules\mongodb\lib\operations\execute_operation.js:12:45
    at maybeCallback (D:\OUWork\Year 6\TM470\Project\node_modules\mongodb\lib\utils.js:338:21)
    at executeOperation (D:\OUWork\Year 6\TM470\Project\node_modules\mongodb\lib\operations\execute_operation.js:12:38)
    at Collection.insertOne (D:\OUWork\Year 6\TM470\Project\node_modules\mongodb\lib\collection.js:148:57)
    at NativeCollection.<computed> [as insertOne] (D:\OUWork\Year 6\TM470\Project\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:226:33)
    at Model.$__handleSave (D:\OUWork\Year 6\TM470\Project\node_modules\mongoose\lib\model.js:309:33)
    at Model.$__save (D:\OUWork\Year 6\TM470\Project\node_modules\mongoose\lib\model.js:388:8)
    at D:\OUWork\Year 6\TM470\Project\node_modules\kareem\index.js:387:18
    at D:\OUWork\Year 6\TM470\Project\node_modules\kareem\index.js:113:15 {
  [Symbol(errorLabels)]: Set(0) {}
}

下面是seeds文件的Javascript代码,供参考:

const mongoose = require('mongoose');
const MusicProduct = require('../database_models/musicproduct');
const BookProduct = require('../database_models/bookproduct');

const musicAlbums = require('./musicseeds');
const bookNovels = require('./bookseeds');

// Connnect to MongoDB
mongoose.connect('mongodb://127.0.0.1/music-bookApp');
mongoose.set('strictQuery', false);

// Logic to check that the database is connected properly
mongoose.connection.on('error', console.error.bind(console, 'connection error:'));
mongoose.connection.once('open', () => {
    console.log('Database connected');
});

//Fill the Music products database with 20 random albums taken from the music seeds file
const musicSeedDB = async () => {
    await MusicProduct.deleteMany({});
    for (let i = 0; i < 20; i++) {
        const randomMusic20 = Math.floor(Math.random() * 20);
        //const musicStock = Math.floor(Math.random() * 10) + 1;
        const musicItem = new MusicProduct({
            artistName: musicAlbums[randomMusic20].artist,
            albumName: musicAlbums[randomMusic20].title,
            //musicStock
        })
        await musicItem.save();
    }
};

//Fill the Book products database with 20 random books taken from the music seeds file
const bookSeedDB = async () => {
    await BookProduct.deleteMany({});
    for (let i = 0; i < 20; i++) {
        const randomBook20 = Math.floor(Math.random() * 20);
        //const bookStock = Math.floor(Math.random() * 10) + 1;
        const bookItem = new BookProduct({
            bookAuthor: bookNovels[randomBook20].authors,
            bookName: bookNovels[randomBook20].title,
            //ookStock
        })
        await bookItem.save();
    }
};

// Close the connection to DB after finish seeding
musicSeedDB().then(() => {
    mongoose.connection.close();
});

bookSeedDB().then(() => {
    mongoose.connection.close();
});

一旦我运行了seeds文件,数据库就会使用seeded信息进行更新,但我更希望在继续之前不要出现错误。
任何帮助都将不胜感激:)
谢谢

nwnhqdif

nwnhqdif1#

musicSeedDB().then(() => {
    mongoose.connection.close();
});

bookSeedDB().then(() => {
    mongoose.connection.close();
});

musicSeedDB完成时,它关闭连接&对于bookSeedDB,连接已经关闭。由于关闭连接会终止与数据库的连接,因此在第一次种子函数调用后调用mongoose.connection.close()将导致连接关闭,这意味着第二次种子函数调用将无法连接到数据库,从而导致MongoNotConnectedError
要解决这个问题,你可以这样做。

Promise.all([musicSeedDB(), bookSeedDB()]).then(() => {
    mongoose.connection.close();
});
jmo0nnb3

jmo0nnb32#

MongoNotConnectedError:当尝试在断开连接的MongoDB客户端上运行数据库操作时,出现“Client must be connected before running operations”错误。要摆脱此错误,您可以尝试以下步骤:
检查您的数据库连接:确保MongoDB客户端已正确连接到数据库。检查连接设置并验证客户端连接到正确的数据库。
重新连接您的客户端:如果您的客户端断开连接,请在运行任何操作之前尝试将其重新连接到数据库。您可以通过调用客户端上的connect()方法来执行此操作。
使用错误处理:使用错误处理来捕获和处理运行数据库操作时可能发生的任何错误。这可以帮助防止“MongoNotConnectedError”首先发生。
检查您的代码:请检查代码以确保正确处理数据库连接和操作。请确保没有试图在断开连接的客户端上运行操作。
通过遵循这些步骤,您应该能够摆脱“MongoNotConnectedError”并在MongoDB客户机上正确地运行数据库操作。

相关问题