MissingSchemaError:尚未为模型“用户”注册架构

时间:2013-12-30 01:29:51

标签: javascript node.js express mongoose

在我的models/user.js文件中:

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

var userSchema = new Schema({
    (define schema)
});
...
(save user)
...
(check password)
...
mongoose.model('User', userSchema);

在我的router/index.js中,我有:

var mongoose = require('mongoose');
var User = mongoose.model('User');

抛出错误:

MissingSchemaError: Schema hasn't been registered for model "User".

但是,如果在user.js中,我(在最后一行)

module.exports = mongoose.model('User', userSchema);

并在index.js我做var User = require('../models/User');,然后一切正常。

但它不应该,因为在config/pass.js我正在做var User = mongoose.model('User');并且它正在完美地运作。

require('../models/User');语法不适用于Ubuntu,但是在我的Mac上。

我该怎么办?我如何解决它?我查看了大量的示例应用,包括MEAN,但没有什么真正有用。

16 个答案:

答案 0 :(得分:52)

我在尝试MEAN教程时遇到了同样的问题。

经过一番研究后,我发现在app.js中,如果我在var routes = require之前放了require(" ./ models / User")(" ./ routes /索引"),然后它的工作原理。

像这样:


mongoose.connect("mongodb://localhost/news");
require("./models/Posts");
require("./models/Comments");

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

希望答案有所帮助!

答案 1 :(得分:36)

发生错误是因为models/user.js在加载时router/index.js尚未解释。解决此问题的一种方法是执行以下操作:

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');

然而,这反映了最佳实践,这要求所有这些配置内容应该在app.js文件的开头发生。从madhums' example project

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

请注意,他在设置应用程序的路由器之前正在加载他的模型。 至于Ubuntu vs Mac问题,我认为这是因为Ubuntu中的相对路径必须以./开头。您只需将其更改为./../models/user.js即可在Mac上使用。

答案 2 :(得分:9)

mongoose架构js文件中的所有代码都应该在其他文件中使用之前运行。

例如,以下代码段确保执行mongoose模式文件/模块。

  

fs.readdirSync(__ dirname +'/ app / model').forEach(functions(file){       if(~file.indexOf('。js'))require(__ dirname +'/ app / models /'+ file); });

可以通过调用

手动执行

或模式文件

  

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

在模型在应用程序的任何地方使用之前

完成上述操作后,可以要求/执行使用mongoose模型的其他模块。

答案 3 :(得分:6)

在加载模型文件加载

之前尝试获取模型时发生此问题

我在 mean.io 项目

中解决了同样的问题

在控制器中:

'use strict';
require('../models/settingsModel'); // load settingsModel.js file before get mongoose.model('Settings')
var mongoose = require('mongoose'),
    Settings = mongoose.model('Settings'),
    Q = require('q');

答案 4 :(得分:2)

在使用快递时,常见的错误之一是在猫鼬之前要求快递。这导致" MissingSchemaError:Schema尚未注册模型" User"。"错误。

您可以通过更正"要求"轻松修复它。顺序(即mongoose然后表达)

var mongoose = require('./config/mongoose'), 
    express = require('./config/express');

答案 5 :(得分:1)

我在尝试使用mongoose-fixture将一些默认数据播种到mongo集合时遇到此错误。被困了很久,跟着这个和类似的线程寻求帮助,试图调试。最终,问题归结为我的mongoosemongoose-fixture版本。

如果没有代码更改帮助,或者在尝试正确使用mongoose-fixture(应该为您注册模式)时遇到此错误,请尝试此操作。删除项目的node_modules目录,运行npm cache clean,然后运行npm install

即使这样做无效,请尝试在有问题的应用和有效应用之间比较mongoose / mongoose-fixture的版本,然后尝试更改package.json中的版本,然后重复以上步骤。这对我有用。

答案 6 :(得分:1)

我从字面上研究了很多东西,我找到了一个解决方案,因此,我将这个解决方案分享给您,因此,没有人可以面对我犯下的那个廉价错误。

请记住,您只需在ref中添加与model中相同的名称,因为它区分大小写(Product!== product)。

const Product = new mongoose.model('Product',productSchema);

product: {
    type: mongoose.Schema.ObjectId,
    ref: 'Product', <-- Should be same as modelName
    required: [true, 'Cart must belong to a product']
}

答案 7 :(得分:0)

尝试在本教程User Auth on MEAN stack的基本代码上添加新模型时遇到此问题。解决方案就像Ahei提到的那样。

具体来说,我需要在require('path/to/your/model')的{​​{1}}末尾添加一行/app_api/models/db.js。为了便于开发,最好保持结构的一致性。

答案 8 :(得分:0)

我最近遇到了一种类似于@ rajkumar-nagarajan和@verybadalloc提供的答案的解决方案。

我更喜欢这种方法,因为它避免了n + 1迭代,并且不会从文件系统中读取所有模型。

app/models/index.js中,需要每个模型文件:

require('./model1');
require('./model2');
require('./model3');

然后,在/app.js/index.js中(无论您的项目使用哪种方式),您现在都可以简单地执行以下操作:

require('./app/models');

我所缺少的部分(在此感谢所有提示)-如何通过名称轻松注册每个模型,例如:

mongoose.model('Model1')

答案 9 :(得分:0)

我也遇到了ES6 / Typescript错误。即使我导入了模型,错误仍然存​​在。根据文档here

MongooseError.MissingSchemaError

  

尝试访问尚未注册的模型时引发

    import { model, Schema } from 'mongoose';
    import Company from './CompanyModel';

    const ProjectSchema = new Schema({
        company: { type: Schema.Types.ObjectId, ref: "Company" }
    });

    export default model('Project', ProjectSchema);

提示只是为了确保明确使用模型,因此将ref:"Company"更改为ref:Company.modelName似乎是固定的。

我希望对您有所帮助

答案 10 :(得分:0)

我犯了一个不同的错误,就像我正确创建了收集模式及其模型一样,但是问题是我没有使用模式模型(用于插入,更新,读取和删除文档)。

即我已经创建了类似的集合:

const playerSchema = new Schema({
    bowling: {
        style: String,
        arm: String,
    }
})

export const PlayerSchema = model('Player', playerSchema)

但未在某处使用或调用PlayerSchema模型,这就是为什么会出现此错误

答案 11 :(得分:0)

  • 您需要在代码中要求您的模型
  • 在调用mongoose.model之前,Mongoose不会识别出您已经定义了模型,只有在需要模型时才会调用

例如

在下面的示例中,如果您不执行MissingSchemaError: Schema hasn't been registered for model “Role”,则会得到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);

答案 12 :(得分:0)

就我而言,这是由于大写/小写字母混乱造成的。 用户模型具有以下内容:

const userSchema = new Schema({
// ...
});
module.exports = mongoose.model('User', userSchema);

“产品”模型引用了“用户”模型,但小写:

const productSchema = new Schema({
// ...
  userId: {
    type: Schema.Types.ObjectId,
    ref: 'user', // This should exactly match the name of User model above!!!
    required: true
  }
});

答案 13 :(得分:0)

我尝试了上述所有解决方案,但所有解决方案均失败了,我发现解决方案是清除数据库(MongoDB),然后重新运行该应用程序

答案 14 :(得分:0)

该问题在模型的require()语句中出现。您需要将所有MongoDB依赖关系移至路由依赖关系之上,例如

//blog.js file

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const blogSchema = new Schema({
title : String
});

mongoose.model('blogs', blogSchema);

在server.js中

//server.js file
require('dotenv').config();
const mongoose = require('mongoose');
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
require('./models/blog');
const Blog = mongoose.model('blogs');

const URL = process.env.MONGO_DB_URL;
 mongoose.connect(URL, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

mongoose.connection
.once('open', () => console.log('Connected to MongoLab instance.'))
.on('error', (error) => console.log('Error connecting to MongoLab:', error));

const app = express();

app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get('/',  (req,res)=>{
res.send('Hello World')
});

 app.post('/blog',async (req, res) =>{
    const blog = await new Blog(req.body).save();
    res.send('just an example');
  });

答案 15 :(得分:-8)

如果您使用的是Mean.js堆栈,请使用以下命令运行测试

grunt test

而不是

mocha