Getting this error - MongoNotConnectedError: Client must be connected before running operations

Hi All,

I have recently started on a project at my University, and part of this project is including a seeds file to seed a DB with test information. Previously, this has worked fine but now I am getting the following error messages every time I run the seeds file in 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. [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) {}
}

Node.js v18.12.1

For reference (if it helps), here is the seeds file I have created and run:

// Code to require the parts needed for seedsindex to work correctly
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();
});

To be fair, the seeds file still seems to run as the database does update with the seeded information, but I would much rather get to the bottom of the error so I can stop it appearing.

Thank you for your help in advance :slight_smile:

Take a look at these two example scripts, first is Node.JS, second is Mongoose.

#!/usr/bin/env node
import { MongoClient } from 'mongodb';
import { spawn } from 'child_process';
import fs from 'fs';

const DB_URI = 'mongodb://0.0.0.0:27017';
const DB_NAME = 'DB name goes here';
const OUTPUT_DIR = 'directory output goes here';
const client = new MongoClient(DB_URI);

async function run() {
  try {
    await client.connect();
    const db = client.db(DB_NAME);
    const collections = await db.collections();

    if (!fs.existsSync(OUTPUT_DIR)) {
      fs.mkdirSync(OUTPUT_DIR);
    }

    collections.forEach(async (c) => {
      const name = c.collectionName;
      await spawn('mongoexport', [
        '--db',
          DB_NAME,
        '--collection',
          name,
        '--jsonArray',
        '--pretty',
        `--out=./${OUTPUT_DIR}/${name}.json`,
      ]);
    });
  } finally {
    await client.close();
    console.log(`DB Data for ${DB_NAME} has been written to ./${OUTPUT_DIR}/`);
  }
}
run().catch(console.dir);

The points I want to drive home with the first, is how the connections to the DB are being established and verified before the rest of the operations. And comparatively to how similar connections work with Mongoose, as you can choose to use Mongoose for redundancy to ensure the client connection if you’d like.

Mongoose:

const mongoose = require('Mongoose');
mongoose.connect("MongoDB://localhost:<PortNumberHereDoubleCheckPort>/<DatabaseName>", {useNewUrlParser: true});
const <nameOfDbschemahere> = new mongoose.schema({
  name: String,
  rating: String,
  quantity: Number,
  someothervalue: String,
  somevalue2: String,
});

const Fruit<Assuming as you call it FruitsDB> = mongoose.model("nameOfCollection" , <nameOfSchemeHere>);

const fruit = new Fruit<Because FruitsDB calling documents Fruit for this>({
  name: "Watermelon",
  rating: 10,
  quantity: 50,
  someothervalue: "Pirates love them",
  somevalue2: "They are big",
});
fruit.save();

Mongoose Script

Could it be because you wrote

await client.close();

1 Like

error === {message : “Client must be connected before running operations”}
i am facing this type of error so many times i worked it but i couldn’t fix that bug

Yes, you are absolutely right…