NodeJS: MongoNotConnectedError: Client must be connected before running operations

23 Views Asked by At

I am experiencing MongoNotConnectedError: Client must be connected before running operations using Mocha to test in NodeJS. In the output it shows database has been connected successfully while actually ran the program, but still not passing the test.

Here is my test:

`import mongoose from 'mongoose'; import { expect } from 'chai'; import importTracks from '../../scripts/importTracks.js'; import { Track } from '../../models/track.js'; import connectDB from '../../database.js';

describe('importTracks', () => { before(async () => { await connectDB(); // Adjust for test database });

after(async () => { await mongoose.disconnect(); });

it('should import tracks from an Excel file', async () => { const filePath = './Track Import Test.xlsx'; // Adjust path as necessary await importTracks(filePath);

const tracks = await Track.find({}); expect(tracks.length).to.be.greaterThan(0);

Additional assertions based on expected test data });

});```

And here is my code:


import dotenv from "dotenv";
dotenv.config({ path: "../.env" }); // Adjust the path as necessary

import mongoose from "mongoose";
import xlsx from "xlsx";
import connectDB from "../database.js"; // Adjust path as necessary
import { Contract } from "../models/contract.js"; // Adjust path and ensure export style matches
import { Track } from "../models/track.js"; // Adjust path and ensure export style matches

const importTracks = async (filePath) => {
await connectDB();

Ensure "Contract 1" exists
let contract = await Contract.findOne({ name: "Contract 1" });
if (!contract) {
contract = new Contract({ name: "Contract 1" });
await contract.save();
  }

Load and read the Excel file
const workbook = xlsx.readFile(filePath);
const sheetName = workbook.SheetNames[0];
const sheet = workbook.Sheets[sheetName];
const data = xlsx.utils.sheet_to_json(sheet);
const errorLog = [];

Process each track
for (const item of data) {
const { Title, Version, Artist, ISRC, PLine, Aliases } = item;
if (!Title || !ISRC) {
if (
ISRC ==
        "Any dashes, spaces or other characters will be stripped out on import"
      ) {
continue;
      }
console.error(
        `Missing required fields for track: ${JSON.stringify(item)}`
      );
errorLog.push(
        `Missing required fields for track: ${JSON.stringify(item)}`
      );
continue;
    }

const aliasesArray = Aliases
Aliases.split(";").map((alias) => alias.trim())
[];

const track = new Track({
title: Title,
version: Version || "",
artist: Artist || "",
isrc: ISRC,
pLine: PLine || "",
aliases: aliasesArray,
contract: contract._id,
    });

try {
await track.save();
console.log(`Track ${Title} imported successfully.`);
catch (error) {
console.error(`Failed to save track: ${Title}. Error: ${error.message}`);
errorLog.push(`Failed to save track: ${Title}. Error: ${error.message}`);
    }
  }

if (errorLog.length > 0) {
console.log("Some errors occurred during import:");
errorLog.forEach((err) => console.log(err));
else {
console.log("All tracks have been imported successfully.");
  }

await mongoose.disconnect();
};

export default importTracks;```

Track.js:
```import mongoose from 'mongoose';

const trackSchema = new mongoose.Schema({
title: { type: String, required: true },
version: String,
artist: String,
isrc: { type: String, required: true },
pLine: String,
aliases: [String],
contract: { type: mongoose.Schema.Types.ObjectId, ref: 'Contract' }
});

Export the Track model as a named export
export const Track = mongoose.model('Track', trackSchema);

Can anyone please help me to troubleshoot where the problem is from?

I am experiencing MongoNotConnectedError: Client must be connected before running operations using Mocha to test in NodeJS.

0

There are 0 best solutions below