MissingSchemaError: Schema hasn't been registered for model “User”

前端 未结 16 1061
别跟我提以往
别跟我提以往 2020-12-02 16:56

In my models/user.js file:

var mongoose = require(\'mongoose\');
var Schema = mongoose.Schema;

var userSchema = new Schema({
    (define schema         


        
16条回答
  •  自闭症患者
    2020-12-02 17:25

    • You'll need to require your model in your code
    • Mongoose won't recognize that you've defined a model until you've called mongoose.model, and that's only called when you require model

    Ex.

    In the below example, you will get MissingSchemaError: Schema hasn't been registered for model “Role” if you don't do const Role = require("./role");

    const mongoose = require("mongoose");
    const Schema = mongoose.Schema;
    const Role = require("./role");
    const userSchema = new Schema(
      {
        role: { type: Schema.Types.ObjectId, ref: "Role", required: false },
        username: { type: String, required: true, trim: true },
        password: { type: String, required: true, trim: true },
        email: { type: String, required: true, trim: true }
      },
      { timestamps: true }
    );
    
    module.exports = mongoose.model("User", userSchema);
    

提交回复
热议问题