Develop a Node.js script that periodically fetches cryptocurrency price data from a public API and saves it to a MongoDB database. The script should run every 15 minutes and store the latest prices for Bitcoin, Ethereum, and Litecoin. Implement error handling and ensure that duplicate entries are not added to the database.
PLAINFORMAT
const axios = require('axios');
const MongoClient = require('mongodb').MongoClient;
const cron = require('node-cron');

const mongoUrl = 'mongodb://localhost:27017';
const dbName = 'crypto_prices';

async function fetchPrices() {
  try {
    const response = await axios.get(
      'https://api.coingecko.com/api/v3/simple/price?ids=bitcoin%2Cethereum%2Clitecoin&vs_currencies=usd'
    );
    return response.data;
  } catch (error) {
    console.error(`Error fetching prices: ${error.message}`);
    return null;
  }
}

async function savePrices(prices) {
  if (!prices) return;

  try {
    const client = await MongoClient.connect(mongoUrl, { useNewUrlParser: true, useUnifiedTopology: true });
    const db = client.db(dbName);
    const collection = db.collection('prices');

    // Check for duplicate entries
    const lastEntry = await collection.findOne({}, { sort: { _id: -1 } });

    if (
      lastEntry &&
      lastEntry.bitcoin === prices.bitcoin.usd &&
      lastEntry.ethereum === prices.ethereum.usd &&
      lastEntry.litecoin === prices.litecoin.usd
    ) {
      console.log('Duplicate entry. Skipping save.');
      await client.close();
      return;
    }

    // Save the new prices to the database
    const result = await collection.insertOne({
      timestamp: new Date(),
      bitcoin: prices.bitcoin.usd,
      ethereum: prices.ethereum.usd,
      litecoin: prices.litecoin.usd,
    });

    console.log(`Saved prices: ${JSON.stringify(result.ops[0])}`);
    await client.close();
  } catch (error) {
    console.error(`Error saving prices: ${error.message}`);
  }
}

cron.schedule('*/15 * * * *', async () => {
  console.log('Fetching and saving cryptocurrency prices...');
  const prices = await fetchPrices();
  await savePrices(prices);
});