Reputation: 603
I am pushing sensor data to a mongoDB server using node.js and express. I'm pushing data around 5 times a second (using HTTP post requests).
I send aggregated sensor data. My sensor data look like this
transmission 1 - 1,2,3
transmission 2 - 4,5,6
transmission 3 - 7,8,9
After appending my data to database, it sometimes looks like this
data array - 1,2,3,7,8,9,4,5,6
As you can see 3rd transmission is appended before 2nd transmission
POST request handling parts of my server.js look like this
var app = require("express")();
app.post("/saveData", function(req, res){
res.send("a");//sending acknowledgement
Data_From_NodeMCU = req.body.hello; //getting data from JSON object
////Some processing\\\\
dbObject.updateOne(
{name: "AKILA"},
{'$push': {data :{$each: processed_data} }},
function (err) {
if (err)
{
console.log("DB error:");
console.log(err);
}
}
);
});
It seems like what i want to achieve is, once app.post is called, stop it from executing again until database is updated. It maybe a basic problem but I'm new to this, any help would be very helpful
Upvotes: 0
Views: 487
Reputation: 4877
You can use async's queue with a concurrency of 1
. It will be something like this:
const app = require("express")();
const queue = require("async/queue");
const q = queue(function(task, cb) {
dbObject.updateOne({name: "AKILA"},
{'$push': {data :{$each: task.processed_data} }}, (err) => {
if (err) console.log("DB error:", err);
cb();
});
}, 1)
app.post("/saveData", function(req, res){
res.send("a"); //sending acknowledgement
const Data_From_NodeMCU = req.body.hello;
const processed_data = processData(Data_From_NodeMCU);
q.push({processed_data});
});
Upvotes: 1