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