Searching for a specific data point within the latest entry of a JSON file using Javascript

I am currently in the process of utilizing a sensor to measure temperature, which is then stored in a mongo database. This data can be accessed as a JSON file by visiting ('/data').

My goal is to determine the latest entry and extract the temperature value from it.

This is an example of how the JSON data appears (x10,000):

{
"_id": {
    "$oid": "5882d98abd966f163e36a6cf"
},
"temperature": 19,
"humidity": 30,
"epochtime": 1484970377120
}

I have configured the website with express.js, and I presume that I will need to parse this JSON object to navigate through it and identify the most recent entry.

for ("temperature" in '/data') {
    output += temperature + ': ' + obj[temperature]+'; ';
}
console.log(output[0]);

Thank you for your assistance.


UPDATE & Solution:

A big thank you to Bertrand Martel for providing an almost flawless solution.

MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected successfully to server");

db.collection('Sensors', function(err, collection){
assert.equal(err, null);
var options = {
  "limit": 1
}
var sort = {
  "epochtime": -1
}

collection.find({}, options).sort(sort).toArray(function(err, res) {
assert.equal(err, null);

console.log("most recent temperature : " + res[0].temperature);
console.log("most recent humidity : " + res[0].humidity);
    }); 
});
db.close();
});

Answer №1

To organize the epochtime in descending order and retrieve only one document:

If utilizing node-mongodb-native:

var MongoClient = require('mongodb').MongoClient;

MongoClient.connect("mongodb://localhost:27017/testDB", function(err, db) {
    if (err) {
        return console.dir(err);
    }

    db.collection('test', function(err, collection) {

        collection.find({}, { "limit": 1 }).sort({ "epochtime": -1 }).toArray(function(err, res) {
            console.log("latest recorded temperature: " + res[0].temperature);
        });

    });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The backbone view is having trouble processing the data from this.model.toJSON()

I've been working on a Backbone code implementation to display all modifications before adding data to my model. However, every time I try to add something from my form, my view returns "this.model.toJSON() is not a function" and I can't figure o ...

Exploring sagas: Faking a response using a call effect

In my current scenario, I am facing a challenging situation: export function* getPosts() { try { const response = yield call(apiCall); yield put({ type: "API_CALL_SUCCESS", response }); } catch(e) { // ... } Furthermore, there is a spec ...

The ui.bootstrap.carousel component seems to be missing from the display

My Carousel is not displaying for some unknown reason. I have customized the implementation based on my project requirements which differ slightly from the standard guidelines. Despite this, it should function correctly as detailed below. By clicking on m ...

When the disk space is insufficient, the createWriteStream function will not trigger an error event if the file is not completely written

One challenge I'm encountering involves using createWriteStream: Imagine I have a large 100mb file that I want to write to another file on the disk. The available space on the disk is only 50mb. Here's my code snippet: const fs = require(&a ...

The failure to load a unicode json/serialized dictionary is the result of a unicode error

Given a specific input that needs to be parsed and converted into a Dict, I have no control over how the input is created. For example, the input could look like u'{u\'my_key\': u\'AB\\N\'}', whi ...

Having difficulty transforming a JSON string into a JSON object using Javascript

Currently, I am working on a hybrid mobile application using Angular. I have a string that is obtained from a $http.jsonp request and I am attempting to convert the response into JSON format. After checking the validity of the JSON at , it appears to be va ...

JavaScript - Issues with Cookie Setting

I created a function for setting cookies: function storeCookie(cname, cvalue, exdays){ var d = new Date(); d.setTime(d.getTime() + (1000*60*60*24*exdays)); var expires = "expires="+d.toGMTString(); document.cookie = cname + "=" + cvalue + ...

Function anomalies triggered by delayed setState updates with React Hooks

Creating a Quiz app with React involves fetching questions as an array and managing the following states: An array containing all question details - statement, options, chosen answer, status (answered, marked for review, unvisited); An object holding info ...

When attempting to navigate to a controller using Express.Router and Passport, encountering an undefined error with req.url.indexOf('?')

The statement "var search = 1 + req.url.indexOf('?');" throws an error indicating that it is undefined. I am currently working on creating a login/registration page using passportjs on my angular frontend. When attempting to make a post request t ...

Python - Organizing massive collection into separate parts

Currently, I am working on processing a map that contains 750 x 750 numbered tiles stored as JSON data. My goal is to retrieve this data and divide each tile into separate arrays or chunks. I have successfully implemented the code for this task; however, ...

I'm receiving an error message stating "mongoose.connect is not a function" while attempting to establish a connection with mongoose. Can you help me troub

I'm a beginner in Node.js and I'm currently working on creating a node/express/mongoose server app using TypeScript. Below is my app.ts file: // lib/app.ts import express from 'express'; import * as bodyParser from 'body-parser&a ...

What is the process for activating a script file once I have replaced HTML content using a backend method?

After receiving HTML content from the backend, including the <script> tags, I noticed that the scripts.js file does not seem to be activated. While the HTML content displays fine, changing the path to style.css successfully alters the appearance of ...

What is the best way to extract data from a basic JSON response using a fetch request

I am encountering an issue with a simple JSON object in my fetch response. When I attempt to access it, the code gets caught in the catch block. this is my response { "islogin": true } fetch(url, data) .then(res => {console.log(res);retur ...

Having Trouble with $.ajax Function in my Program

After spending three days experimenting with various methods, I'm still unable to successfully use the Javascript ajax command to send form values to a php script. Despite no errors being displayed and the scripts running smoothly, nothing is getting ...

Dealing with JSON Codable in Swift 4 can be tricky, as the value returned can vary between being an object

When retrieving data from an API, it sometimes returns a single object, but other times it returns an array with the same key. The current model (struct) I am using for decoding fails when an array is returned. The order of these results is random, so I c ...

Dropdown list remains open despite a selection being made

My problem arises when I attempt to select an item from the list, as the dropdown menu does not populate automatically and the list remains open. Here is the HTML code for the dropdown list: <label id='choose' for='options'>Sele ...

Generating a preview image for a three.js environment

I am currently working on a website dedicated to visualizing the biological neurons found in animals. I have a comprehensive list of neuron names, and I use THREE JS to draw the neuron when the user clicks on its name. However, with hundreds of neurons to ...

What is React.js's approach to managing CSS files?

Currently, I am enrolled in Bootcamp at Scrimba where they utilize an online platform for teaching various courses. One of the topics covered is React and involves working with CSS files. When working on my local machine, I typically use the index.css file ...

Top method for identifying browser window modifications such as navigating back, altering the URL, refreshing, or closing the window

Currently, I am developing a testing application that requires me to trigger a finsihTheTest() function in specific situations. These situations include: When the user attempts to reload the page. When the user tries to navigate back from the page. If the ...

Decipher Base64 encoded values during the process of JSON deserialization

I'm currently working on a Java application that interacts with an API to retrieve JSON data. The values in the JSON response are encoded in Base64 format. Here is a snippet of the JSON data (although there are many more key-value pairs): { "id_e ...