【问题标题】:unable to insert user data into database无法将用户数据插入数据库
【发布时间】:2022-01-20 14:52:53
【问题描述】:

我正在尝试将用户数据插入到我的数据库中,但数据没有插入,并且显示为用户已存在于此电子邮件中 这个怎么解决? 我的代码如下 我尝试过使用不同的电子邮件,即使它是用户已经存在于这封电子邮件中并且它没有插入到数据库中。

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;

请查找附件图片

【问题讨论】:

  • 只是想知道为什么你有reactjs这个问题的标签?!
  • @Amir-Mousav 错误

标签: javascript node.js mongoose


【解决方案1】:

查询数据库是一个异步函数调用。 在auth.js,如果用户退出,您正在检查异步。 const user = User.findOne({ email: req.body.email }); 你应该像这样添加等待:const user = await User.findOne({ email: req.body.email }); 因为,它的 asyncourouns Javascript 不会等待答案并将 undefined 分配给用户变量。 因此,您最终会使用 else 语句。

【讨论】:

    猜你喜欢
    • 2012-04-13
    • 2013-03-02
    • 2021-07-23
    • 2017-10-24
    • 2015-02-22
    • 1970-01-01
    相关资源
    最近更新 更多