如何在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.) toNumbertype—this lets you run queries like "find all entries wherelast> 2700000" without extra parsing. - Converted the
attimestamp (seconds since epoch) to aDatetype—MongoDB has great built-in support for date queries (e.g., fetching data from the last 24 hours). - Added optional
enumconstraints to enforce valid values for fields likebase_unitortype—remove these if you plan to support other coins/pair types later. - Added an index on
atto 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:
- Make sure MongoDB is running locally (or update the connection string to your remote MongoDB instance).
- Install dependencies:
npm install express mongoose. - Run the server:
node server.js. - Send a POST request to
http://localhost:3000/api/crypto/btcinrwith your raw JSON data as the body.
Bonus Tips
- Avoid Duplicate Entries: If you're fetching data periodically, use
findOneAndUpdatewithupsert: trueto 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-scheduleto 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
atfield 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
相关产品推荐
相关产品推荐

