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();
});
});
};