Home > front end >  koa react simple CRUD
koa react simple CRUD

Time:06-29

This is the backend I created for add a new students and also this includes the login and registry files. All the crud operations are working properly. But I want to know the whether I used the correct file structure

When I am running the application this error has occured; MongooseError: The uri parameter to openUri() must be a string, got "undefined". Make sure the first parameter to mongoose.connect() or mongoose.createConnection() is a string.

I used mongoose to connect the database

The student model have the all necessary values.

controller has the CRUD implementation

routes has the paths of the CRUD operations

**index.js**

    require("dotenv").config();
    const Koa = require("koa");
    const KoaRouter = require("koa-router");
    const cors = require("@koa/cors");
    const bodyParser = require("koa-bodyparser");
    const json = require("koa-bodyparser");
    const { dbConnect } = require("./utils/dbConnect");
    const courseRoutes = require("./routes/course.routes");
    const studentRoutes = require("./routes/student.routes");
    
    const app = new Koa();
    const router = new KoaRouter();
    
    app.use(cors());
    app.use(bodyParser());
    app.use(json());
    app.use(router.routes()).use(router.allowedMethods());
    app.use(courseRoutes.routes());
    app.use(studentRoutes.routes());
    
    router.get("/", (ctx) => {
      ctx.body = { message: "Student Management API" };
    });
    
    app.listen(9000, () => {
      dbConnect();
      console.log(`Server is up and running on http://localhost:9000`);
    });

**Student.Controller**

    const Student = require("../models/student.model");
    const Course = require("../models/course.model");
    
    const addStudent = async (ctx) => {
      try {
        const { name, nic, age, courseId } = ctx.request.body;
        const student = await Student.create({
          name,
          nic,
          age,
          courseId,
        });
    
        await Course.findByIdAndUpdate(courseId, { $push: { students: student._id } });
        return (ctx.body = student);
      } catch (error) {
        return (ctx.body = { message: error.message });
      }
    };
    
    const getStudents = async (ctx) => {
      try {
        const students = await Student.find().populate({
          path: "courseId",
          select: "courseName courseFee",
        });
        return (ctx.body = students);
      } catch (error) {
        return (ctx.body = { message: error.message });
      }
    };
    
    const updateStudent = async (ctx) => {
      try {
        const studentId = ctx.params.studentId;
        const { name, nic, age, courseId } = ctx.request.body;
    
        const student = await Student.findByIdAndUpdate(studentId, {
          name,
          nic,
          age,
          courseId,
        });
    
        await Course.findByIdAndUpdate(student.courseId, {
          $pull: { students: studentId },
        });
    
        await Course.findByIdAndUpdate(courseId, {
          $push: { students: studentId },
        });
    
        return (ctx.body = student);
      } catch (error) {
        return (ctx.body = { message: error.message });
      }
    };
    
    const deleteStudent = async (ctx) => {
      try {
        const studentId = ctx.params.studentId;
    
        const student = await Student.findById(studentId);
    
        await Course.findByIdAndUpdate(student.courseId, { $pull: { students: studentId } });
        await Student.findByIdAndDelete(studentId);
        return (ctx.body = student);
      } catch (error) {
        return (ctx.body = { message: error.message });
      }
    };
    
    module.exports = {
      addStudent,
      getStudents,
      updateStudent,
      deleteStudent,
    };

**Student.Model**

    const mongoose = require("mongoose");
    
    const StudentSchema = new mongoose.Schema({
      name: { type: String, required: true },
      nic: { type: String, required: true },
      age: { type: Number, required: true },
      courseId: { type: mongoose.Schema.Types.ObjectId, required: false, ref: "courses" },
    });
    
    const Student = mongoose.model("students", StudentSchema);
    
    module.exports = Student;


**Student.route**

    const KoaRouter = require("koa-router");
    const {
      addStudent,
      getStudents,
      updateStudent,
      deleteStudent,
    } = require("../controller/student.controller");
    const router = new KoaRouter({ prefix: "/student" });
    
    router.post("/add", addStudent);
    router.delete("/:studentId", deleteStudent);
    router.put("/:studentId", updateStudent);
    router.get("/", getStudents);
    
    module.exports = router;

**Student.login.controller**

    const User = require("../models/user.model");
    
    const registerUser = async (ctx)=>{
        try {
            const { useremail,userpassword} = ctx.request.body;
    
            if(!useremail || !userpassword){
                 throw new Error("Please provide all values");
            }
    
            const alreadyExist = await User.findOne({useremail});
    
            if(alreadyExist){
                 throw new Error("Already Exisits");
            }
    
            const user = await User.create({useremail,userpassword});
            return (ctx.body = user);
        } catch (error) {
             return (ctx.body = {message:error.message});
        }
    };
    
    const login = async (ctx)=>{
        try {
            const { useremail, userpassword } = ctx.request.body;
    
            if (!useremail || !userpassword) {
              throw new Error("Please provide all values");
            }
            const user = await User.findOne({useremail});
            const matchPassword = await User.findOne({ userpassword });
    
            if(!user ||!matchPassword){
                 ctx.throw (401,"Invalid credentials");
            }
            
            return (ctx.body = user);
        } catch (error) {
             return (ctx.body = { message: error.message });
        }
    };
    
    module.exports={
        registerUser,
        login,
    }


**Db connect**

    const mongoose = require("mongoose");
    
    const dbConnect = () => {
      const dbConStr = process.env.MONGODB_URL;
    
      mongoose.connect(dbConStr, () => {
        console.log("Database connected");
      });
    };
    
    module.exports = { dbConnect };

CodePudding user response:

U have to give the path for .env file in index.js

require('dotenv').config({ path: 'src/.env' });
  • Related