Debug School

rakesh kumar
rakesh kumar

Posted on

Store data as object data type in node js

student names in a dropdown and their marks as checkboxes from an input field. We'll store the data in Node.js as parent-child relationships (student name as parent and subject marks as children) using an object data type. For this example, we'll use Express.js as the Node.js server and MongoDB as the database.

Step 1: Set up the Node.js server with Express.js and MongoDB
Install the required dependencies:

npm install express mongoose body-parser
Enter fullscreen mode Exit fullscreen mode

Create a file named app.js for the Node.js server:

const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');

const app = express();
app.use(bodyParser.json());

mongoose.connect('mongodb://localhost:27017/mydatabase', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

const studentSchema = new mongoose.Schema({
  name: { type: String, required: true },
  marks: { type: Object, required: true },
});

const Student = mongoose.model('Student', studentSchema);

app.post('/api/students', async (req, res) => {
  try {
    const { name, marks } = req.body;
    const newStudent = new Student({ name, marks });
    await newStudent.save();
    res.status(201).json({ message: 'Student data saved successfully' });
  } catch (error) {
    res.status(500).json({ error: 'Failed to save student data' });
  }
});

app.listen(5000, () => {
  console.log('Server is running on port 5000');
});
Enter fullscreen mode Exit fullscreen mode

Step 2: Set up the React.js front-end
Create a new React app and set up the components:

npx create-react-app react-app
cd react-app
npm install axios
Enter fullscreen mode Exit fullscreen mode

Replace the content of src/App.js with the following code:

import React, { useState, useEffect } from 'react';
import axios from 'axios';

const App = () => {
  const [studentName, setStudentName] = useState('');
  const [subjectMarks, setSubjectMarks] = useState({});
  const [students, setStudents] = useState([]);

  useEffect(() => {
    axios.get('/api/students').then((response) => {
      setStudents(response.data);
    });
  }, []);

  const handleAddStudent = () => {
    axios
      .post('/api/students', { name: studentName, marks: subjectMarks })
      .then(() => {
        setStudentName('');
        setSubjectMarks({});
      })
      .catch((error) => console.error('Error saving student data:', error));
  };

  return (
    <div>
      <h1>Student Database</h1>
      <div>
        <label>Student Name:</label>
        <input
          type="text"
          value={studentName}
          onChange={(e) => setStudentName(e.target.value)}
        />
      </div>
      <div>
        <label>Subject Marks:</label>
        <input
          type="checkbox"
          name="math"
          checked={subjectMarks.math || false}
          onChange={(e) =>
            setSubjectMarks((prevMarks) => ({
              ...prevMarks,
              math: e.target.checked,
            }))
          }
        />
        <label>Math</label>
        <input
          type="checkbox"
          name="science"
          checked={subjectMarks.science || false}
          onChange={(e) =>
            setSubjectMarks((prevMarks) => ({
              ...prevMarks,
              science: e.target.checked,
            }))
          }
        />
        <label>Science</label>
        {/* Add more subjects as needed */}
      </div>
      <button onClick={handleAddStudent}>Add Student</button>

      <div>
        <h2>Students:</h2>
        <ul>
          {students.map((student) => (
            <li key={student._id}>
              <strong>{student.name}</strong>
              <ul>
                {Object.entries(student.marks).map(([subject, mark]) => (
                  <li key={subject}>
                    {subject}: {mark ? 'Pass' : 'Fail'}
                  </li>
                ))}
              </ul>
            </li>
          ))}
        </ul>
      </div>
    </div>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

Step 3: Run the application
Start both the Node.js server and React.js app:

Start the Node.js server
node app.js

cd react-app
npm start
Enter fullscreen mode Exit fullscreen mode

Now, you have a React.js app running on http://localhost:3000 with a form to add student data. When you add a student's name and select the subject marks using checkboxes, the data will be sent to the Node.js server and stored in the MongoDB database as parent-child relationships. The student name is the parent, and the subject marks are stored as children in an object data type. The student data will then be fetched from the database and displayed on the React front-end.

Top comments (0)