Utilize the accurate information retrieved from the API and store it in MongoDB

I have a functioning script that automatically sends data to my MongoDB every second, but I am struggling with figuring out how to send the exact data from an API to MongoDB.

FULL CODE

    var requestPromise = require('request-promise');
const { MongoClient } = require('mongodb');
const schedule = require('node-schedule');
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;

var j = schedule.scheduleJob('* * * * * *', function() {
    var burl = "https://api.binance.com/api/v3/ticker/24hr?symbol=BTCUSDT";

    var ourRequest = new XMLHttpRequest();

    ourRequest.open('GET', burl, true);
    ourRequest.onload = function() {
        var x1 = JSON.parse(ourRequest.responseText)
        var btcdata = (x1.volume)
        console.log(btcdata);
        saveToDatabase(btcdata);
    }
    ourRequest.send();
});

const saveToDatabase = function(BTC) {

    const url = 'mongodb+srv://Hexynator:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dca8b9afa8edeeef9cbfb0a9afa8b9aeecf1edb7a9b2aef2b1b3b2bbb3b8bef2b2b9a8">[email protected]</a>/<dbname>?retryWrites=true&w=majority';

    MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }, (err, db) => {
        if (err) throw err;
        const dbo = db.db('Crypto');
        const myobj = { Name: 'BTC', Volume: 'Volume' };
        dbo.collection('Crypto-Values').insertOne(myobj, (error, res) => {
            if (error) throw error;
            console.log('1 document inserted');
            db.close();
        });
    });
};

The issue seems to be in this line of code:

const myobj = { Name: 'BTC', Volume: 'Volume' };

This is what it looks like in the MongoDB collection https://i.sstatic.net/HCjSf.png

I also tried changing it to -

const myobj = { Name: 'BTC', Volume: btcdata };
But I got this error -
ReferenceError: btcdata is not defined

Question: How can I change 'Volume' to be a number retrieved from the API here - console.log(btcdata);

Goal: To have BTC as the name in the database and Volume as the number fetched from the API.

Answer №1

function addToDatabase(BTCdata) {
    const databaseURL = 'mongodb+srv://username:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5916081a1818100716170a0e1118011655194b145c404115414449411541484019">[email protected]</a>/<dbname>?retryWrites=true&w=majority';

    MongoClient.connect(databaseURL, { useNewUrlParser: true, useUnifiedTopology: true }, (err, db) => {
        if (err) throw err;
        const dbo = db.db('Crypto');
        const myobj = { Name: 'BTC', Volume: BTCdata };
        dbo.collection('Crypto-Values').insertOne(myobj, (error, res) => {
            if (error) throw error;
            console.log('Successfully inserted 1 document');
            db.close();
        });
    });
};

Prior to this change, the input data (BTCdata) was not being utilized within the function.

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

React App searching for unused static files

Currently, my React application is deployed on the Nginx web server. Accessing the application using the URL XX.XX.XX.XX works fine. However, I want to be able to access it through the URL XX.XX.XX.XX/myapp/frontend. To achieve this, I have set up a revers ...

Tips on generating a sample Mongoose Model with all null values

Imagine you are working with the following schema: var userSchema = new Schema({ name: String, schools: [{ level: String, name: String, timeInterval: { start: {type:Date,default:Date.now}, ...

replace specific elements for cloze deletion evaluation

Consider this scenario: There are many reasons to succeed. (consisting of more than 5 words) phrases = ['There', 'are', 'many', 'reasons', 'to', 'succeed'] flashcards_count = ceil(len(phrase) / 3 ...

Bidirectional data binding in AngularJS custom directive

I have recently started working with Angular.js and I am attempting to create a custom directive with a controller containing functions that is connected to another controller. I want the object in the main controller ($scope.MyObj) to update in sync wit ...

Angular Boilerplate is experiencing difficulties in properly reading ABP

Working on my boilerplate project, I am now diving into consuming backend services (using asp .net) in Angular through http requests. However, I encountered an issue when trying to implement the delete method in mycomponent.ts, as TypeScript was not recogn ...

Preserve numerous inputs in local storage

Hope your day is going well. I've been attempting to save multiple inputs by parsing localStorage into JSON using a 'for' loop, but unfortunately, nothing is being saved. The error message in the CONSOLE reads: "Uncaught SyntaxError: Unexpe ...

The raycaster fails to detect collision with the .gltf model

When using the raycaster to detect mouse intersection with a cube, everything works perfectly: raycaster.setFromCamera(mouse, camera) const intersects = raycaster.intersectObject(cubeMesh) if(intersects.length > 0) console.log('intersecting ...

Execute a Python script using an Ajax jQuery call

Recently, I encountered an issue when attempting to execute a python file via jQuery. To address this problem, I conducted research online and came across a specific code snippet designed to call and run a python script. Below is the AJAX code utilized fo ...

Implement a sequence of animations within a div using jQuery

My goal is to create an animation effect for each div element within a row when the user scrolls down to that specific point on the page. The layout consists of three <div> elements in the same row. The structure of the HTML code is as shown below: ...

Setting radio button selection programmatically in React Material-UI: A step-by-step guide

Currently utilizing a radio button group from material-ui. I have successfully set a default selection using defaultSelected, however, after rendering, I am unable to programmatically change it. The selection only updates upon clicking the radio. Is ther ...

Click on the button to send the input field

Below you'll find an input field and a button: <input id="pac-input" class="controls" type="text" placeholder="Search! e.g. Pizza, Pharmacy, Post office"> <button id="new" class="btn btn-success">Submit</button> Currently, when te ...

Making a Zoom effect using p5.js

I have searched for a solution to this question multiple times, but none of the answers I came across seem to work for me. Currently, I am able to allow the user to scale an image with a simple scale(factor) call. However, now I am attempting to implement ...

Creating HTML inputs dynamically using jQuery in an ASP.NET application

I have written this JavaScript code to dynamically generate and add HTML elements within my asp.net webform: var i = 0; function addFields() { i++; var quantity = '<td class="auto-style2"><input type="text" size="3" name= ...

Verify if a request attribute has been established using jQuery

How can I determine if an attribute is present in a request object? I have specific error scenarios where an error message needs to be sent to the client side: Here is the servlet code snippet: request.setAttribute("error", "The following term was not fo ...

The getInitialProps function in Next.js is not functioning properly in mobile browser environments

My app runs perfectly on desktop without any errors. However, when I switch to a mobile device, I noticed that the pages fail to trigger the getInitialProps method on the client side, only if I navigate through the Link component. This is my code: return( ...

Issue with Mongoose Populate function failing to retrieve requested data during data retrieval operations

My platform consists of two main models: category and story. The story model contains a reference id linking to the corresponding category. Within the story controller, there is a specific function called mystories designed to retrieve all story records ...

The console log message persists even though the condition statement is present - Vue2

The main goal of my code is to trigger the fetchNumbers() function (which retrieves numbers from an API) when a user scrolls to the bottom of the page, creating an infinite scroll effect. However, I'm encountering an issue with the condition inside th ...

The scrolling behavior of Chrome tabs or bookmarks can impact the functionality of an Angular

I recently came across a strange problem with my angularjs page that includes a slick carrousel. In the controller, I have code that listens for the $destroy event to remove certain injected elements by slick. However, I noticed that whenever I scroll ov ...

Select any menu option to return to the one-page layout and then scroll down to find the location

I'm wondering if there is a way to navigate back from an external page to a specific section on my one-page website with a fixed menu? On my one-pager website, I have a fixed menu that includes a "apply for a job" button. When clicked, it takes users ...

After the ajax request is made in React JS, the column vanishes from the screen

Upon querying a node.js server's PostgreSQL database, I receive specific data that needs to be displayed in two separate tables. Each table consists of two columns. However, after the AJAX call, only the first column is being populated in the first ta ...