From 2a99a49608bde5567398701e7bbac12dcb286d18 Mon Sep 17 00:00:00 2001 From: varun Date: Thu, 6 Jul 2023 02:59:57 -0400 Subject: [PATCH] storing only 3 records based on hardwareid --- src/controllers/tanksController.js | 28 +++++++++++++++++++++------- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index 72575968..5daa4320 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -958,6 +958,7 @@ exports.calculateCapacity = async (req, reply) => { }; + exports.IotDevice = async (req, reply) => { try { const { hardwareId, mode, tanks } = req.body; @@ -973,20 +974,32 @@ exports.IotDevice = async (req, reply) => { tankHeight: tank.tankHeight, maxLevel: tank.maxLevel, minLevel: tank.minLevel, - date:date, - time:time + date: date, + time: time })); - // create a new IOttank document with the provided data + // create a new IotData document with the provided data const ottank = new IotData({ hardwareId, mode, tanks: tankDocuments, date, time }); // save the document to MongoDB await ottank.save(); - // get the latest document sorted in descending order of date and time - const latestOttank = await IotData.findOne({ hardwareId }).sort({ date: -1, time: -1 }); - // send the latest document - reply.code(200).send({ latestOttank }); + // delete previous records except the three latest ones + const previousRecords = await IotData.find({ hardwareId }) + .sort({ date: -1, time: -1 }) + .skip(3); // skip the three latest documents + + for (const record of previousRecords) { + await record.remove(); + } + + // get the latest three documents sorted in descending order of date and time + const latestOttanks = await IotData.find({ hardwareId }) + .sort({ date: -1, time: -1 }) + .limit(3); + + // send the latest documents + reply.code(200).send({ latestOttanks }); } catch (err) { // send an error response reply.code(500).send({ error: err.message }); @@ -994,6 +1007,7 @@ exports.IotDevice = async (req, reply) => { }; + exports.getIotD = async(req, reply) => { try { await IotData.find({hardwareId: req.query.hardwareId})