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.