我正在尝试创建用户模型,但是却遇到了MissingSchemaError

时间:2019-05-07 11:09:29

标签: node.js mongoose-schema

我正在尝试在Node.js和Mongoose中创建用户模型,但出现错误:

MissingSchemaError : Schema hasn't been registered for the model "user"

我已尝试通过以下站点的帮助来解决此问题,但它对我而言不起作用。

How to register and call a schema in mongoose

https://github.com/Automattic/mongoose/issues/3105

用户模型

const mongoose = require("mongoose");

const UserSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true,
    unique: true
  },
  password: {
    type: String,
    required: true
  },
  avatar: {
    type: String
  },
  status: {
    type: Boolean,
    default: false
  },
  date: {
    type: Date,
    default: Date.now
  }
});

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

user.js

const express = require("express");
const gravatar = require("gravatar");
const bcrypt = require("bcryptjs");
const router = express.Router();
const { check, validationResult } = require("express-validator/check");
// const User = require("../../models/User");

// @route POST api/users
// @desc Register user
// @access Public

    enter code here`
router.post(
  "/",
  [
    check("name", "Name is required")
      .not()
      .isEmpty(),
    check("email", "Please include valid Email").isEmail(),
    check(
      "password",
      "Please enter a password with 6 or more characters"
    ).isLength({
      min: 6
    })
  ],
  async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      console.log(errors);
      return res.status(400).json({ errors: errors.array() });
    }

    const { name, email, password } = req.body;

    try {
      let user = await User.findOne({ email });
      if (user) {
        res.status(400).json({
          errors: [{ msg: "User Already Exists" }]
        });
      }

      const avatar = gravatar.url(email, {
        s: "200",
        r: "pg",
        d: "mm"
      });

      user = new User({
        name,
        email,
        avatar,
        password
      });

      const salt = await bcrypt.genSalt(10);

      user.password = await bcrypt.hash(password, salt);

      await user.save();

      res.send("User Route");
    } catch (err) {
      console.error(err.message);
      res.status(500).send("Sever Error");
    }
  }
);

如何创建此模型?

2 个答案:

答案 0 :(得分:0)

注册模型时,尝试将用户更改为大写用户,并在User之后删除module.exports,如下所示:

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

答案 1 :(得分:0)

实际上,您没有在模型中传递架构,而是传递字符串“ UserSchema”,而应该传递UserSchema

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

并要求

const {User} = require(PATH TO MODEL)