How to use collection in MQTT onMessage event

Hi,
its probably something stupid but Im struggling with that for second day, unable to find some working solution.

I have mqttjs client listening subscribed to topic and want to update collection when message is received, but if I use findOne in method called from onMessage listener, I always get “Fatal error occurred: MongoNotConnectedError: Client must be connected before running operations”

const connectDB = async () => {
    try {
        await client.connect();
        db = client.db(DBNAME);
        sensors = db.collection('sensors');
      } catch (e) {
        console.error(e);
    }
}
...
 mqttClient.on("message", (topic, message) => {
             handleMessage(topic, message);
});
...

const handleMessage = (topic, message) => {
 ... extract sensorId ..

  sensors.findOne({ id: sensorId }) 
    .then(result => console.log(`handleMessage ${result}`))
    .catch(err => console.error(`Fatal error occurred: ${err}`)); <==== MongoNotConnectedError
}

I tried promise variant because on message is not async, connect call is fine, same method works when used in other locations, just here in message call I’ve got not connected client errror.

Thanks for any hint!

Roman

Hello @Roman_Hosek according to the code flow seems like the connection for mongo is in a function names as connectDB but you have not called the function, hence mongo connection will not be initialized, also i have used asyn/await
`let db, sensors;

const connectDB = async () => {
try {
await client.connect();
db = client.db(DBNAME);
sensors = db.collection(‘sensors’);
console.log(“MongoDB connected”);
} catch (e) {
console.error(“Error connecting to MongoDB:”, e);
}
};

// Ensure connection is established before handling messages
const handleMessage = async (topic, message) => {
const sensorId = … // Extract sensorId from the message or topic
try {
if (!db) {
throw new Error(“Database not connected”);
}

    const result = await sensors.findOne({ id: sensorId });
    if (result) {
        console.log(`Sensor found: ${result}`);
    } else {
        console.log("Sensor not found");
    }
} catch (err) {
    console.error(`Fatal error occurred: ${err}`);
}

};

// Connect to MongoDB
connectDB();

// Set up MQTT listener
mqttClient.on(“message”, (topic, message) => {
handleMessage(topic, message);
});
`
Tell me if this will help

Dennis