Node.js初学者求助:提取API返回的vehicleLocations并插入数据库
vehicleLocations Data and Insert into a Database (Node.js Beginner Guide) Hey there! I'll walk you through both tasks clearly since you're just starting out with Node.js.
1. Extracting the vehicleLocations Data
First, let's assume your API response is stored in a variable (let's call it apiResponse). Your data is an array with one object inside, so accessing the vehicleLocations property is straightforward:
// Your API response data const apiResponse = [ { "rowId": "0", "group": "RBEIBAN:SMP", "zoomLevel": "12", "latitude": "12.955081", "vehicleLocations": [ { "rowId": 0, "latitude": "12.955081", "longitude": "77.641369", "speed": 0 }, { "rowId": 1, "latitude": "12.936186", "longitude": "77.611698", "speed": 0 } ] } ]; // Extract vehicleLocations const vehicleLocations = apiResponse[0].vehicleLocations; console.log(vehicleLocations); // This will log the array of vehicle location objects you need
If there's a chance the API could return multiple objects in the top-level array, you can collect all vehicleLocations into one single array like this:
const allVehicleLocations = apiResponse.flatMap(item => item.vehicleLocations); // flatMap merges all nested vehicle arrays into one
2. Inserting the Data into a Database
I'll cover two common databases used with Node.js: MySQL (relational) and MongoDB (NoSQL) — pick the one that fits your project.
Option 1: MySQL (using mysql2 library)
First, install the dependency:
npm install mysql2
Then write code to connect and insert your data (replace placeholder values with your actual database details):
const mysql = require('mysql2/promise'); async function insertVehicles() { // Create a database connection const connection = await mysql.createConnection({ host: 'your-db-host', user: 'your-db-user', password: 'your-db-password', database: 'your-db-name' }); try { // Adjust the query to match your table's column names const insertQuery = 'INSERT INTO vehicle_locations (rowId, latitude, longitude, speed) VALUES (?, ?, ?, ?)'; // Loop through each vehicle and insert it for (const vehicle of vehicleLocations) { await connection.execute(insertQuery, [vehicle.rowId, vehicle.latitude, vehicle.longitude, vehicle.speed]); } console.log('All vehicle locations inserted successfully!'); } catch (error) { console.error('Oops, something went wrong inserting data:', error); } finally { // Always close the connection when done await connection.end(); } } // Run the function insertVehicles();
Option 2: MongoDB (using mongodb native driver)
Install the dependency first:
npm install mongodb
Then connect to your MongoDB instance and insert the data:
const { MongoClient } = require('mongodb'); async function insertVehicles() { // Replace with your MongoDB connection string (local or Atlas) const uri = 'mongodb://your-mongo-host:27017'; const client = new MongoClient(uri); try { await client.connect(); const db = client.db('your-db-name'); const vehicleCollection = db.collection('vehicle_locations'); // Insert all vehicle locations in one go const result = await vehicleCollection.insertMany(vehicleLocations); console.log(`${result.insertedCount} vehicle locations added to the database!`); } catch (error) { console.error('Error inserting data:', error); } finally { // Close the connection await client.close(); } } // Run the function insertVehicles();
A quick reminder: Make sure your database table/collection is set up with matching fields (like latitude, longitude, etc.) before running the insertion code.
内容的提问来源于stack exchange,提问作者user9172381

