diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index fa2b0fb6..c26bb282 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -663,21 +663,36 @@ exports.IotDevice = async (req, reply) => { try { const { hardwareId, tankHeight, maxLevel, minLevel, mode } = req.body; - // create a new tank document - const tank = new IotData({ hardwareId, tankHeight, maxLevel, minLevel, mode }); + // create a new tank document with the current date and time + const currentDate = new Date(); + const date = currentDate.toLocaleDateString('en-IN'); + const time = currentDate.toLocaleTimeString('en-IN', {hour12:false, timeZone: 'Asia/Kolkata' }); + const tank = new IotData({ hardwareId, tankHeight, maxLevel, minLevel, mode, date, time }); // save the document to MongoDB await tank.save(); - // send a success response - reply.code(200).send({ message: 'Data saved successfully' }); + // get all the tank documents for the current hardwareId sorted in descending order of date and time + const tanks = await IotData.find({ hardwareId }).sort({ date: -1, time: -1 }); + + // if the number of documents for the current hardwareId is greater than three, remove the oldest documents until there are only three left + if (tanks.length > 3) { + const oldestDocuments = tanks.slice(3); + for (const doc of oldestDocuments) { + await IotData.deleteOne({ _id: doc._id }); + } + } + + // get the latest three tank documents for the current hardwareId sorted in descending order of date and time + const latestTanks = await IotData.find({ hardwareId }).sort({ date: -1, time: -1 }).limit(3); + + // send the latest three documents in descending order of date and time + reply.code(200).send({ latestTanks: latestTanks.reverse() }); } catch (err) { // send an error response reply.code(500).send({ error: err.message }); } -} - - +}; exports.getIotD = async(req, reply) => { diff --git a/src/models/tanks.js b/src/models/tanks.js index 508f688d..9ac69bb2 100644 --- a/src/models/tanks.js +++ b/src/models/tanks.js @@ -46,8 +46,13 @@ const IOttankSchema = new mongoose.Schema({ tankHeight: { type: String, required: true }, maxLevel: { type: String, required: true }, minLevel: { type: String, required: true }, + date: { type: String, required: true }, + time: { type: String, required: true }, mode: { type: Number, required: true } }); + + +