Next Auth - Saving user to MongoDB
Unanswered
Orinoco Crocodile posted this in #help-forum
Orinoco CrocodileOP
asd
2 Replies
Orinoco CrocodileOP
API:
Model:
import connectDB from "@/lib/monogdb";
import User from "@/models/User";
import { NextResponse } from "next/server";
import bcrypt from "bcryptjs";
connectDB();
export async function POST(request) {
try {
// Access Req Body
const reqBody = await request.json();
const { name, rno, username, password, role, image } = reqBody;
console.log(reqBody);
// Check if user already exists
const user = await User.findOne({ username });
if (user) {
return NextResponse.json(
{ message: "User already exists" },
{ status: 400 }
);
}
// // Check if rno already exists
const r_no = await User.findOne({ rno });
if (r_no) {
return NextResponse.json(
{ message: "Roll Number already exists" },
{ status: 400 }
);
}
// // Hash password
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(password,salt);
// Create new user
const newUser = new User({
name,
rno,
username,
password: hashedPassword,
role,
image,
});
// // Save user to DB
const savedUser = await newUser.save();
console.log(savedUser);
return NextResponse.json({ message: "User created successfully" });
} catch (error) {
return NextResponse.json({ error: error.message }, { status: 500 });
}
}Model:
import mongoose from "mongoose";
const userSchema = new mongoose.Schema(
{
name: {
type: String,
required: true,
},
rno: {
type: String,
required: true,
},
username: {
unique: true,
type: String,
required: true,
},
password: {
type: String,
required: true,
},
role: {
type: String,
required: true,
},
image: {
type: String,
required: true,
},
},
{ timestamps: true }
);
const User = mongoose.models.User || mongoose.model("User", userSchema);
export default User;POST /auth/register 400 in 8ms
{
name: 'JohnKeats',
rno: 'assd1a',
username: 'asdd',
password: 'yopp1234a5a',
role: 'yop',
image: 'https://www.gravatar.com/avatar'
}
{
username: 'asdd',
role: 'yop',
password: '$2a$10$6seXetoaXtJot9wfLeCjduqfXOS5xHtMO6QvIuql9oAXj.68bkqPe',
_id: new ObjectId('66ae7a7f73f135dcfb828156'),
__v: 0
}
POST /auth/register 200 in 72msI'm expected to add 6 fields in the database, but only user role pass is saving