I have a Mqtt client subscribing to a topic. When the subscriber receives message, the on_message callback starts working. I have a mongoose query based on the message inside the on_message callback. That query is taking too long to execute.
However, keeping the query outside the on_message callback executes immediately. But I want it inside the callback.
Here is my code sample -
var mqtt = require('mqtt');
mqttClient = mqtt.connect("mqtt://broker.emqx.io:1883",{clientId:"mqttClient", keepalive: 1000});
let options = {
retain:false,
qos:1};
mqttClient.subscribe('topic' ,{qos:1});
mqttClient.on('message', async function (topic, message){
let msg = JSON.parse(message);
msg.forEach(async letter => {
let dev = await Device.find({
letters: letter}).lean();
})
});
mqttClient.publish('topic', JSON.stringify(['a', 'b', 'c', 'd', 'e', 'f']), options);
here, dev
query is the one taking too long.
As @hardillb suggested, I removed the query from the callback and queried somewhere else. Using query callback also does not help, it is still taking too long. I strongly believe it is because of mongoose. Because I tried the same with mongodb and it is more faster as the usual query would behave.