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

前端 未结 16 1064
别跟我提以往
别跟我提以往 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:29

    The error occurs because the models/user.js has not been interpreted by the time router/index.js has been loaded. One way to solve this would be to do the following:

    var mongoose = require('mongoose');
    //Load all your models
    var User = require('./../models/user.js');
    
    //Now, this call won't fail because User has been added as a schema.
    mongoose.model('User');
    

    This, however, turns out to be against best practises, which dictates that all this config stuff should happen at the start of your app.js file. Look at this example from madhums' example project

    var models_path = __dirname + '/app/models'
    fs.readdirSync(models_path).forEach(function (file) {
      if (~file.indexOf('.js')) require(models_path + '/' + file)
    })
    

    Note that he is loading his models before setting the app's router. As for the Ubuntu vs Mac issue, I believe it is because a relative path in Ubuntu has to start with ./. You just have to change it to ./../models/user.js, which works on Mac.

    0 讨论(0)
  • 2020-12-02 17:29

    If you are using the Mean.js stack, run the test with:

    grunt test
    

    And not with

    mocha
    
    0 讨论(0)
  • 2020-12-02 17:30

    In using express, one of the common mistake is by requiring the express before mongoose. This results to "MissingSchemaError: Schema hasn't been registered for model "User"." error.

    You can easily fix it by correcting the "require" order (i.e mongoose then express)

    var mongoose = require('./config/mongoose'), 
        express = require('./config/express');
    
    0 讨论(0)
  • 2020-12-02 17:31

    All code in your mongoose schema js files should have run before it is used in other files.

    For example, the following code snippet makes sure the mongoose schema files/modules are executed.

    fs.readdirSync(__dirname + '/app/models').forEach(function (file) { if (~file.indexOf('.js')) require(__dirname + '/app/models/' + file); });

    or schema files can be manually executed by calling

    var User = require('./app/models/user.js')

    before the models are used anywhere in the application.

    Once the above is done, other modules that uses mongoose models can be required/executed.

    0 讨论(0)
提交回复
热议问题