Search code examples
javascriptnode.jsmongodbmongoose

Error MongoNotConnectedError: Client must be connected before running operations - how to get rid of the error?


I am creating a project where I am using a seeds file to seed my DB with test data.

When I run the file in node.js, here is the error I get:

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) {}
}

For reference, here is the Javascript code for the seeds file:

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

Once I run the seeds file, the database gets updated with the seeded information, but I would much prefer the error not be there before moving on.

Any help would be appreciated :)

Thanks


Solution

  • Replace this code

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

    to

    await musicSeedDB();
    await bookSeedDB();