Home > Mobile >  Create User function is not working in node.js using express
Create User function is not working in node.js using express

Time:01-07

below is where my function is, and the createUser is not working, until const {firstName, id} = req.body is working the name and id show up but don't create the user. If you need more informations just ask. Thank you!

const { PrismaClient } = require("@prisma/client");
    
    const prisma = new PrismaClient();
    
    module.exports = {
        async createUser(req, res) {
            try {
                const {firstName, id} = req.body
                console.log({firstName, id}) //until here is working the name and id show up but don't create the user
        
                const user = await prisma.UserInfo.create({
                    data: {
                        firstName,
                        id
                    }
                });
    
                return res.json(user)
        
            } catch (error) {
                return res.json({error})
                
            }
        },
    
        async teste(req, res) {
            try {
                return res.json("again")
            }
            catch(error) {
                return res.json({error})
            }
        }
    }

that image show what error show up in my screen

here is my routes

const express = require("express");
const UserController = require("./UserController");
let router = express.Router();

router.post("/user",  UserController.createUser);

module.exports = router

here is my server

const express = require('express');
const router = require('./routes.js');
const app = express();

app.use(express.json())

app.use(require("./routes.js"))
app.listen(3333, () => {
    console.log('server at port 3333 is running');
});

here is my schema in prisma

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider          = "sqlserver"
  url               = env("DATABASE_URL")
  shadowDatabaseUrl = env("DATABASE_SHADOW_URL")
}

model UserInfo {
  id        Int     @id @default(autoincrement())
  firstName String?
  lastName  String?
  email     String  @unique
  password  String
  age       Int
  role      String?
}

CodePudding user response:

You have passed the object to prisma.UserInfo.create() method.

As per my understanding after seeing the error message, You need to pass the properties email, password, and age to Prisma.UserInfo.create() with the property id and firstName.

Here the problem is, When you going to create the record in the userInfo table, you have only passed the property id and firstName. But in your database migration, you set that like email, password, and age these things are not going to be null.

So the following properties must be passed to prisma.UserInfo.create() method

const {email, password, age, firstName} = req.body;

prisma.UserInfo.create({
  data: {email, password, age, firstName // firstName is optional
  }
});

  • Related