【问题标题】:Mongoose validation error, "email is not defined"Mongoose 验证错误,“未定义电子邮件”
【发布时间】:2021-06-25 03:37:02
【问题描述】:

我是猫鼬和快递的新手。我尝试创建一个简单的登录后端,但是当使用

发送帖子请求时

{ “用户邮箱”:“abc@xyz”,“密码”:“pswrd” }

我收到类型为“验证”的“电子邮件未定义”错误。我的用户架构如下:

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

const UserSchema = new mongoose.Schema({
  email: {
    type: String,
    required: [true, "Email is required"],
    trim: true,
    unique: true,
  },
  password: {
    type: String,
    trim: true,
    required: [true, "Password is required"],
  },
  username: {
    type: String,
    required: [true, "Username is required"],
    trim: true,
    unique: true,
  },
});

UserSchema.pre("save", async function (next) {
  const user = await User.findOne({ email: this.email });
  if (user) {
    next(new Error(`${this.email} already taken`));
    return;
  }

  const user1 = await User.findOne({ username: this.username });
  if (user1) {
    next(new Error(`${this.username} already taken`));
    return;
  }

  const salt = await bcrypt.genSalt(8);
  this.password = await bcrypt.hash(this.password, salt);
  next();
});

// userSchema.statics is accessible by model
UserSchema.statics.findByCredentials = async (email, password) => {
  const user = await User.findOne({ email });
  if (!user) {
      throw Error("User does not exist.");
  }
  const isMatch = await bcrypt.compare(password, user.password);
  if (!isMatch) {
      throw Error("Unable to login");
  }

  return user;
};

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

我使用 findByCredentials 检查用户是否在我的 mongoDB 数据库中。最后我的login.js如下:

const express = require("express");
const mongoose = require("mongoose");
const User = require("../db/models/User");

const loginRouter = express.Router();

loginRouter.get("/api/login2", (req, res) => res.send("In Login"));

loginRouter.post("/api/login", async (req, res) => {
  const { userEmail, password} = req.body;

  if (!validateReqBody(userEmail, password)) {
    return res
      .status(401)
      .send({ status: false, type: "INVALID", error: "invalid request body" });
  }

  try {

    const newUser = new User({
        email: userEmail,
        password: password,
    });
    await newUser.findByCredentials(email, password);
} catch (error) {
    const validationErr = getErrors(error);
    console.log(validationErr);
    return res
      .status(401)
      .send({ status: false, type: "VALIDATION", error: validationErr });
  }

    res.send({ status: true });
});

//user.find --> mongoose documentation

// Validates request body
const validateReqBody = (...req) => {
  for (r of req) {
    if (!r || r.trim().length == 0) {
      return false;
    }
  }
  return true;
};


// Checks errors returning from DB
const getErrors = (error) => {
  if (error instanceof mongoose.Error.ValidationError) {
    let validationErr = "";
    for (field in error.errors) {
      validationErr += `${field} `;
    }
    return validationErr.substring(0, validationErr.length - 1);
  }
  return error.message;
};


module.exports = { loginRouter };

谢谢。

【问题讨论】:

  • 打印出req.body的值,如果为空则需要注册body parse
  • @hoangdv 您好,感谢您的回复。我刚刚打印出req.body,它不是空的,和我发送post请求的方式一样。

标签: node.js mongodb express mongoose mongoose-schema


【解决方案1】:

findByCredentials() 的定义在用户模型中。我试图通过我在 login.js 中创建的对象实例 newUser 来访问该函数。但是,我应该将该函数称为 User.findByCredentials(email, password)。

【讨论】:

    【解决方案2】:

    你需要在后端使用 body-parser 中间件

    const bodyParser = require('body-parser');
    const express = require('express');
    const app = express();
    
    //bodypraser middleware
    app.use(bodyParser.json());
    

    您可以阅读有关 bodyparser 的更多信息here

    【讨论】:

      【解决方案3】:

      曾经发生在我身上,真的很烦人。我不知道它是否会对您有所帮助,但请尝试使用fetch 发送带有headers: { 'Content-Type': 'application/json' }, 的发布请求。

      【讨论】:

        猜你喜欢
        • 2023-03-14
        • 1970-01-01
        • 1970-01-01
        • 2014-12-19
        • 2022-12-05
        • 1970-01-01
        • 1970-01-01
        • 2021-05-26
        • 1970-01-01
        相关资源
        最近更新 更多