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

Uncertain about the ins and outs of AJAX

I am a complete beginner in web development. Although I have studied JavaScript and HTML through books, my understanding is still limited. I have never worked with AJAX before and find most online examples too complex for me to follow. My goal is to crea ...

What could be the reason for JavaScript code successfully exporting to Excel using the old office extension .xls but encountering issues when trying to export

I am currently working on exporting an HTML table to Excel using JavaScript. I have encountered an issue where it does not export to the newer version of Excel with the xlsx extension. However, it works fine and exports to older versions of Excel with the ...

How can I use ngx-editor to insert an HTML block at the current cursor position by clicking a button?

I am currently using ngx-editor within Angular 7. My goal is to insert HTML at the cursor's position upon clicking on parameters from a list. The current view displays how the parameter is appended when clicked, as shown in the image attached . My de ...

Transforming JavaScript to TypeScript in Angular: encountering error TS2683 stating that 'this' is implicitly of type 'any' due to lacking type annotation

While in the process of migrating my website to Angular, I encountered an error when attempting to compile the JS into TS for my navbar. After searching around, I found similar issues reported by other users, but their situations were not quite the same. ...

What is the equivalent of Node's Crypto.createHmac('sha256', buffer) in a web browser environment?

Seeking to achieve "feature parity" between Node's Crypto.createHmac( 'sha256', buffer) and CryptoJS.HmacSHA256(..., secret), how can this be accomplished? I have a piece of 3rd party code that functions as seen in the method node1. My goal ...

Tips for saving/downloading generated QR codes in React Native

Using this code allows me to generate QR Codes, but I am struggling with saving the generated QR Code in PNG or JPEG format. I have tried a few examples without success and I am continuing to try different methods. import React, { Component } from 'r ...

Providing structured Express app to deliver HTML and JavaScript content

Currently, I am working with Express and facing a seemingly simple challenge. Here is the structure of my directories: |-config |---config.js |---routes.js |-server.js |-scripts |---controllers |------controllers.js |---directive ...

Retrieve a JSON feed from an external streaming source using Node.js

Using Node.js, I've been working with stream-chain and stream-json to stream feeds from both local and remote sources. The code below successfully handles local resources, but how can I modify it to work with external resources as well? Should I downl ...

What strategies can I use to streamline this array update function code?

Looking to simplify my updated array function. The update function involves updating and comparing values in an array. The comparison will be done within the fruit_temp. For example, data in fruit_temp's fruit_db_id corresponds to an existing id in th ...

Organize information in a React table following a predetermined sequence, not based on alphabetical order

As a beginner with React, I'm looking to sort my data by the column "Status" in a specific order (B, A, C) and vice versa, not alphabetically. The data structure looks like this: export interface Delivery { id: number; name: string; amount: num ...

The Ajax function effortlessly receives the returned value and smoothly transitions to the error handling stage

When trying to retrieve data from an ajax request, my function needs to receive the returned data as an array of strings. During debugging, I am able to see the response, but at the same time, the error function is triggered. This is how my code looks: ...

Modifying the value property of the parent element

Here is an example of the HTML code I am working with: <td value='3' style='text-align: center'> <select class='selection' onchange=''> <option value='1'>1</option> <opti ...

Dashing List JSON Summary

In my current project, I'm setting up a Dashing job to retrieve data from an API using Ruby. SCHEDULER.every '15m', :first_in => 0 do |job| url = "https://blah.com" response = RestClient.get(url, {:Authorization => 'blahb ...

Creating a central navigation menu for a website

Currently, I am working on incorporating a menu in the center of a webpage (please note that this is not a top navigation menu). Here is the initial setup: Users are able to click on various menu items to access different content. I have written code fo ...

Guide on setting up and customizing run.json within the latest JetBrains Fleet for Next.js

I've been attempting to set up input/output for the latest IDE from JetBrains, Fleet. However, I've hit a roadblock and can't seem to figure it out on my own. That's why I'm turning to the Stack Overflow community for help - how do ...

Looking for the final entry in a table using AngularJS

Hey everyone, I'm dealing with a table row situation here <tbody> <tr *ngFor="let data of List | paginate : { itemsPerPage: 10, currentPage: p }; let i = index"> <td>{{ d ...

Discover the steps to linking a dropdown menu to a text input using HTML and JavaScript

I'm currently using Sublime and trying to link a dropdown menu with an input text using html, css, and javascript. When the user selects an option from the dropdown menu, I want the corresponding value to appear in the text input field. For example, i ...

Issue with Jest Test Trigger Event Not Invoking Method

Currently, I am in the process of writing tests for my Vue application. One particular test involves a button that triggers a logout function. The goal is to determine if the function is executed when the button is clicked. Initially, I attempted to mock ...

Animate CSS Grid to dynamically fill the viewport on top of current grid elements

Please note that I am specifically seeking vanilla JS solutions, as jQuery is not compatible with this project I have a grid structure that is somewhat complex: body { margin: 0; height: 100vh; text-align: center; } .grid-container { ...

Jasmine spies falsely report the calling of functions when they have not actually been called

Below is the code snippet I am currently working with: $scope.deleteJob = function(job) { SandboxService.deleteJob(job.id).then(res => { if (res.status == 200) { ngToast.success(); $scope.refreshApps(); } ...