You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在MongoDB中存储API返回的btcinr对象:Schema创建与保存API实现方法

How to Store BTC-INR Crypto Market Data in MongoDB with Schema & API Endpoint

Got it, let's walk through exactly how to set this up. We'll use Mongoose (for schema validation) and Express (for the API) since they're the most common tools for this kind of task with MongoDB and Node.js.

Step 1: Create a Mongoose Schema for BTC-INR Data

First, we need to define a schema that matches your data structure, with proper data types (note: your raw data has numeric values as strings—we'll convert those to actual numbers for easier querying/aggregation later).

Here's the schema:

const mongoose = require('mongoose');

// Define the nested BTC-INR schema
const BTCINRSchema = new mongoose.Schema({
  base_unit: {
    type: String,
    required: true,
    enum: ['btc'] // Optional: restrict to only BTC if you don't plan to add other coins
  },
  quote_unit: {
    type: String,
    required: true,
    enum: ['inr'] // Optional: restrict to INR
  },
  low: { type: Number, required: true },
  high: { type: Number, required: true },
  last: { type: Number, required: true },
  type: {
    type: String,
    required: true,
    enum: ['SPOT'] // Optional: restrict to SPOT type
  },
  open: { type: Number, required: true },
  volume: { type: Number, required: true },
  sell: { type: Number, required: true },
  buy: { type: Number, required: true },
  at: {
    type: Date,
    required: true,
    index: true // Add index for fast time-based queries
  },
  name: {
    type: String,
    required: true,
    enum: ['BTC/INR'] // Optional: restrict to BTC/INR pair
  }
});

// Option 1: If you want to store each BTC-INR entry as a standalone document
const BTCINR = mongoose.model('BTCINR', BTCINRSchema);

// Option 2: If you need to wrap it under a top-level `btcinr` key (matches your raw data structure)
// const MarketDataSchema = new mongoose.Schema({
//   btcinr: BTCINRSchema
// });
// const MarketData = mongoose.model('MarketData', MarketDataSchema);

module.exports = BTCINR; // Or MarketData if you went with Option 2

Key Notes:

  • Converted string numeric values (low, high, etc.) to Number type—this lets you run queries like "find all entries where last > 2700000" without extra parsing.
  • Converted the at timestamp (seconds since epoch) to a Date type—MongoDB has great built-in support for date queries (e.g., fetching data from the last 24 hours).
  • Added optional enum constraints to enforce valid values for fields like base_unit or type—remove these if you plan to support other coins/pair types later.
  • Added an index on at to speed up time-based queries.

Step 2: Build the Express API Endpoint to Save Data

Next, we'll create a POST endpoint that accepts your raw API data, processes it (converts strings to numbers, timestamp to Date), and saves it to MongoDB.

Here's the full server code:

const express = require('express');
const mongoose = require('mongoose');
const BTCINR = require('./models/btcinr'); // Import your model

const app = express();
app.use(express.json()); // Parse JSON request bodies

// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/crypto_market_db', {
  useNewUrlParser: true,
  useUnifiedTopology: true
})
.then(() => console.log('Successfully connected to MongoDB'))
.catch(err => console.error('MongoDB connection failed:', err));

// API endpoint to save BTC-INR data
app.post('/api/crypto/btcinr', async (req, res) => {
  try {
    // Extract the btcinr object from the request body
    const rawBTCData = req.body.btcinr;

    // Process the data: convert strings to numbers, timestamp to Date
    const processedData = {
      ...rawBTCData,
      low: parseFloat(rawBTCData.low),
      high: parseFloat(rawBTCData.high),
      last: parseFloat(rawBTCData.last),
      open: parseFloat(rawBTCData.open),
      volume: parseFloat(rawBTCData.volume),
      sell: parseFloat(rawBTCData.sell),
      buy: parseFloat(rawBTCData.buy),
      at: new Date(rawBTCData.at * 1000) // Convert seconds to milliseconds for Date
    };

    // Create and save the document
    const newBTCEntry = new BTCINR(processedData);
    await newBTCEntry.save();

    // If using Option 2 (wrapped under btcinr key):
    // const newMarketEntry = new MarketData({ btcinr: processedData });
    // await newMarketEntry.save();

    res.status(201).json({
      message: 'BTC-INR data saved successfully',
      data: newBTCEntry
    });
  } catch (error) {
    res.status(400).json({
      error: 'Failed to save data',
      details: error.message
    });
  }
});

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

How to Test This:

  1. Make sure MongoDB is running locally (or update the connection string to your remote MongoDB instance).
  2. Install dependencies: npm install express mongoose.
  3. Run the server: node server.js.
  4. Send a POST request to http://localhost:3000/api/crypto/btcinr with your raw JSON data as the body.

Bonus Tips

  • Avoid Duplicate Entries: If you're fetching data periodically, use findOneAndUpdate with upsert: true to either update an existing entry (if the timestamp is the same) or create a new one:
    await BTCINR.findOneAndUpdate(
      { at: processedData.at }, // Match by timestamp
      processedData,
      { upsert: true, new: true } // Create if not exists, return updated doc
    );
    
  • Add Scheduled Data Fetching: Use a library like node-schedule to automatically fetch data from your crypto API and save it to MongoDB at regular intervals (e.g., every 5 minutes).
  • Query Historical Data: With the at field as a Date, you can easily fetch data from a time range:
    const last24HoursData = await BTCINR.find({
      at: { $gte: new Date(Date.now() - 24 * 60 * 60 * 1000) }
    });
    

内容的提问来源于stack exchange,提问作者Mohi007

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 20:33:13