Saving the information into a designated MongoDB repository with a particular title

One of my recent projects involved creating a script that pulls data from the Binance API and sends it to MongoDB. This script runs every hour using the Node-Schedule package, fetching three different sets of data based on their symbols (BTCUSDT, ETHUSDT, ATOMBTC). I also developed another script that automatically stores this incoming data in a MongoDB collection.

My goal is to store specific data in specific collections. My idea was to use an if statement to match the symbol name with the collection name. For instance:

if the symbol name matches the collection name => save to that collection

Would this approach be effective for managing three symbols and three collections, each with identical names?

The Full Code


var today = new Date();
 var date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
 var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
 var dateTime = date + ' ' + time;

 var symbols = ["BTCUSDT", "ETHUSDT", "ATOMBTC"];
 let cnt = 0;

 const callIt = () => {
     fetch(`https://api.binance.com/api/v3/klines?symbol=${symbols[cnt]}&interval=1h&limit=1`)
         .then(res => res.json())
         .then(data => {
             const btcusdtdata = data.map(d => {
                 return {
                     Open: parseFloat(d[1]),
                     High: parseFloat(d[2]),
                     Low: parseFloat(d[3]),
                     Close: parseFloat(d[4]),
                     Volume: parseFloat(d[5])
                 }
             });
             console.log(btcusdtdata);
             saveToBTCUSDT(btcusdtdata);
             cnt++;
             if (cnt < symbols.length) setTimeout(callIt, 3000)
         })
         .catch((err) => {
             console.log(err);

         })

 };
 const j = schedule.scheduleJob('0 * * * *', callIt)


     const saveToBTCUSDT = function(BTCdata) {

         const url = 'mongodb+srv://username:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="feeceff6e7e9ebeefeebebcba8ebfafe3deecfff28aebe7">[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('CryptoCurrencies');
             const myobj = { Name: 'BTCUSDT', Array: BTCdata, Date: dateTime };
             dbo.collection('BTCUSDT').insertOne(myobj, (error, res) => {
                 if (error) throw error;
                 console.log('1 document inserted');
                 db.close();
             });
         });
 };

Answer №1

If you pass the current index (count) as a parameter, you can then access the desired collection using that index.

    ...
    saveToBTCUSDT(btcusdtdata, cnt);
    ...

    const saveToBTCUSDT = function(BTCdata, index) {

     const url = 'mongodb+srv://username:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d1a1b0a2a2a6bea3b591b2bda4a2a5b4a3e1fce0baa4bfa3ffbcbebfb6beb5b3ffbfb4a5">[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('CryptoCurrencies');
         const myobj = { Name: symbols[index], Array: BTCdata, Date: dateTime };
         dbo.collection( symbols[index] ).insertOne(myobj, (error, res) => {
             if (error) throw error;
             console.log('1 document inserted');
             db.close();
         });
     });
   };

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

Leveraging ng-switch for template swapping

I'm currently facing an issue in my Angular app where I want to switch from a "sign in" form to a "sign up" form when the user clicks on the "Sign Up" button, but nothing happens upon clicking the button. The sign-in form persists on the screen withou ...

Buffering ceases on the video

I am experiencing an issue with 4 videos and a preloader, which should hide once all the videos are fully buffered. <div id="preload"> <h1> Download... </h1> </div> <video preload="auto" class= ...

When using Javascript template literals, they function properly when assigned to a variable, but they do not work when included in a JSON

Trying to get a grasp of Javascript. Let's say I have a variable declared with template literals: var templateObject = `Student name is ${filteredJSONExample.name} and student age is ${filteredJSONExample.age}.` This functions correctly as sh ...

The button colors in Material Ui do not update properly after switching themes

React Material UI is being utilized in this project. Although the theme is being overridden, the colors of buttons and inputs remain unchanged. Here is how the Material UI theme is created in theme.js // @flow import { createMuiTheme } from '@materi ...

In JavaScript, unchecking a radio button results in all options becoming uncheckable

I have a pure CSS accordion and I want to enhance it with some JavaScript functionality for users who have JavaScript enabled. The CSS accordion currently utilizes the :checked pseudo-class. The new feature I am looking to add is: if a button that is alre ...

Adding a badge to a div in Angular 6: What you need to know!

How can I add a badge to a specific div in Angular 6? I have dynamic div elements in my HTML. I want to increase the counter for a specific div only, rather than increasing it for all divs at once. For example, I have five divs with IDs div1, div2, div3, ...

Why might the Bootstrap menu be malfunctioning?

The reality is that Bootstrap is functional and widely used. Sharing the code could make a big difference in getting assistance! <ul class="top-header-contact-info secondary-menu"> <li class="nav-item dropdown-toggle"> ...

using javascript to create two choices

I am facing a small complication between two select options in my javascript code. Here is the snippet of my javascript: function displayVals() { var singleValues = $("select option:selected").text(); //to stay selected $("#hiddenselect").val(s ...

Ways to combine duplicate entries within a column using Ruby on Rails?

I need some help with a filtering issue related to sign names. I am trying to merge the content together if there is more than one name of the sign. You can refer to the image attached for better clarity, where I have two server names but I only want to di ...

What is the process for utilizing the TypeScript compiler with nodejs?

I have a sample code saved in a file called hello.ts Upon the completion of nodejs setup on Windows, execute the following command to install typescript: npm install -g typescript Is there a way to compile hello.ts directly with node.js? While using "T ...

The clash between mootools and jQuery

I'm facing an issue with a simple form on a page that loads both Mootools and JQuery. Even though JQuery is in no conflict mode, I am encountering problems. There's a form input named "name"-- <input class="required" id="sendname" name="send ...

Is there a way to mount or unmount a React component by pressing a single key?

I am currently developing an application that showcases 3D objects upon pressing certain keys on the keyboard. My goal is to have these objects disappear after 2-3 seconds or once the animation completes. Below is the component responsible for managing th ...

Deciphering Files with NodeJs AES Encryption and Redirecting to a Stream

I am currently working on encrypting a file in C# and decrypting it in Node.js using AES encryption. The code snippet below demonstrates the successful decryption process, however, it writes the decrypted content to an output file named `output_dec.xml&apo ...

At times, the AngularJS directive may not be invoked

Here is my custom directive: ppm.directive('focusMe', function($timeout) { return { link: function(scope, element, attrs) { scope.$watch(attrs.focusMe, function(value) { if(value === true) { console.log(& ...

Vue.js computed property experiencing a minor setback

I'm currently working on developing a test-taking system using Vue and Laravel. When a user inputs the test code and email address, they are directed to the test page. To display all the test questions based on the entered code, I implemented a naviga ...

Create a JavaScript and jQuery script that will conceal specific div elements when a user clicks on them

Within my navigation div, there exists another div called login. Through the use of JavaScript, I have implemented a functionality that reveals additional divs such as login_name_field, login_pw_field, register_btn, do_login_btn, and hide_login upon clicki ...

React.js "universal" component that is able to be generated multiple instances of

I'm struggling to fully understand this problem. Here's the issue: imagine there is an app where I need to generate notifications, dialogs, or other similar elements from my code. One option is to have a "global" component that controls everyth ...

Tips for customizing the Electron title bar and enabling drag functionality

Currently, I am embarking on an electron project and my goal is to incorporate a unique custom frame at the top. Does anybody possess knowledge on how this can be achieved? To further clarify, here is a visual representation of what I envision for the cust ...

The JSON data lacks compatibility with the usage of track by functionality

I am working on a project that involves three connected select menus. The first one displays series names, the second one displays chapter numbers belonging to the series selected in the first menu, and the third one displays page numbers belonging to t ...

Assigning attributes to inner components in VueJS based on prop values

Experimenting with some common VueJS syntax, but I am struggling to get this Button.vue SFC to function properly: <script setup> defineProps({ ... href: String, ... }); </script> ... <template> <Link :href="href&quo ...