Home > Blockchain >  unable to insert user data into database
unable to insert user data into database

Time:12-18

i am try to inser user data into my database but data is not inserting and it is showing like User already exist with this email How can solve this one ? My code is below i had tried with different email even though it is User already exist with this email and it is not inserting in the database.

server.js

require("dotenv").config();
const express = require("express");
const app = express();
const mongoose = require("mongoose");

const port = process.env.PORT || 3500;

app.use(express.json());

//DB connection
mongoose
  .connect(process.env.MONGO_URL)
  .then(() => console.log("DB Connection Successful"))
  .catch((err) => console.log(err));

//Routes

app.use("/api/auth/", require("./routes/auth"));

app.listen(port, () => {
  console.log("Server is running on Port "   port);
});

user.js

const mongoose = require("mongoose");
const bcrypt = require("bcrypt");

const userSchema = new mongoose.Schema(
  {
    firstName: { type: String, required: true, trim: true, min: 3, max: 30 },
    lastName: { type: String, required: true, trim: true, min: 3, max: 30 },
    userName: {
      type: String,
      required: true,
      trim: true,
      min: 3,
      max: 30,
      unique: true,
      index: true,
      lowercase: true,
    },
    email: {
      type: String,
      required: true,
      trim: true,
      unique: true,
      lowercase: true,
    },
    userPassword: { type: String, required: true },
    role: { type: String, enum: ["user", "admin"], default: "admin" },
    contactNumber: { type: String },
    profilePicture: { type: String },
  },
  { timestamps: true }
);

userSchema.virtual("password").set(function (password) {
  this.userPassword = bcrypt.hashSync(password, 10);
});

userSchema.methods = {
  authenticate: function (password) {
    return bcrypt.compareSync(password, this.userPassword);
  },
};

module.exports = mongoose.model("User", userSchema);

auth.js

const router = require("express").Router();
const User = require("../models/user");

router.post("/signin", (req, res) => {});

router.post("/register", async (req, res) => {
  const user = User.findOne({ email: req.body.email });
  if (!user) {
    const newUser = new User(req.body);
    await newUser.save();
    res.status(201).json({
      user: newUser,
    });
  } else {
    res.status(400).json({
      message: "User already exist with this email",
    });
  }
});

module.exports = router;

please find the attached images enter image description here

CodePudding user response:

Querying the database is an asynchronous function call. Here at the auth.js, You're checking asynchronous if the user exits. const user = User.findOne({ email: req.body.email }); You should add await like that: const user = await User.findOne({ email: req.body.email }); Since, its asyncourouns Javascript doesn't wait for the answer and assings undefined to the user variable. Therefore you end up at your else statement.

  • Related