node.js Mongoose Schema 尚未注册模型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26818071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mongoose Schema hasn't been registered for model
提问by arash moeen
I'm learning the mean stack and when I try to start the server using
我正在学习平均堆栈,当我尝试使用
npm start
I get an exception saying that:
我得到一个例外说:
schema hasn't been registered for model 'Post'. Use mongoose.model(name, schema)
here is my code inside /models/Posts.js
这是我在 /models/Posts.js 中的代码
var mongoose = require('mongoose');
var PostSchema = new mongoose.Schema({
title: String,
link: String,
upvotes: { type: Number, default: 0 },
comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }]
});
mongoose.model('Post', PostSchema);
as I can see the schema should be registered for the model 'Post', but what can be possibly causing the exception to be thrown?
正如我所看到的,应该为模型“Post”注册模式,但是什么可能导致抛出异常?
Thanks in advance.
提前致谢。
Edit:Here's the exception error
编辑:这是异常错误
/home/arash/Documents/projects/personal/flapper-news/node_modules/mongoose/lib/index.js:323
throw new mongoose.Error.MissingSchemaError(name);
^
MissingSchemaError: Schema hasn't been registered for model "Post".
Use mongoose.model(name, schema)
and here's the app.js code with the mongoose initialization:
这是带有 mongoose 初始化的 app.js 代码:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/news');
require('./models/Posts');
require('./models/Comments');
before the line:
行前:
app.use('/', routes);
回答by user8264
It's not an issue with model export. I had the same issue.
这不是模型导出的问题。我遇到过同样的问题。
The real issue is that require statements for the models
真正的问题是模型的 require 语句
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/news');
require('./models/Posts');
require('./models/Comments');
were below the routes dependencies. Simply move the mongoDB dependencies above the routes dependencies. This is what it should look like:
低于路由依赖项。只需将 mongoDB 依赖项移动到路由依赖项之上。它应该是这样的:
// MongoDB
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/news');
require('./models/Posts');
require('./models/Comments');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
回答by Rafael Grilli
If someone coudn't fix it with the approach of the correct answer (like me), try to look at the creation of the schema. I wrote the 'ref' as 'User', but the correct was 'user'.
如果有人无法使用正确答案的方法(如我)修复它,请尝试查看模式的创建。我将“ref”写为“User”,但正确的是“user”。
Wrong:
错误的:
createdBy: {
type: Schema.Types.ObjectId,
ref: 'User'
}
Correct:
正确的:
createdBy: {
type: Schema.Types.ObjectId,
ref: 'user'
}
回答by user3616725
IF YOU USE MULTIPLE mongoDB CONNECTIONS
如果您使用多个 mongoDB 连接
beware that when using .populate() you MUST provide the model as mongoose will only "find" models on the same connection. ie where:
请注意,在使用 .populate() 时,您必须提供模型,因为 mongoose 只会在同一连接上“找到”模型。即在哪里:
var db1 = mongoose.createConnection('mongodb://localhost:27017/gh3639');
var db2 = mongoose.createConnection('mongodb://localhost:27017/gh3639_2');
var userSchema = mongoose.Schema({
"name": String,
"email": String
});
var customerSchema = mongoose.Schema({
"name" : { type: String },
"email" : [ String ],
"created_by" : { type: mongoose.Schema.Types.ObjectId, ref: 'users' },
});
var User = db1.model('users', userSchema);
var Customer = db2.model('customers', customerSchema);
Correct:
正确的:
Customer.findOne({}).populate('created_by', 'name email', User)
or
或者
Customer.findOne({}).populate({ path: 'created_by', model: User })
Incorrect(produces "schema hasn't been registered for model" error):
不正确(产生“模式尚未为模型注册”错误):
Customer.findOne({}).populate('created_by');
回答by kuldipem
I used the following approach to solve the issue
我使用以下方法来解决问题
const mongoose = require('mongoose');
const Comment = require('./comment');
const PostSchema = new mongoose.Schema({
title: String,
link: String,
upvotes: { type: Number, default: 0 },
comments: [{ type: mongoose.Schema.Types.ObjectId, ref: Comment }]
});
mongoose.model('Post', PostSchema);
Please look, here refdon't have stringtype value, now it's referring to Commentschema.
请看,这里ref没有string类型值,现在它指的是Comment模式。
回答by 100RaBH
This error also pops up when we create wrong references (ref) between mongoose models.
当我们在猫鼬模型之间创建错误的引用 (ref) 时,也会弹出此错误。
In my case I was referring to the file name instead of model name.
就我而言,我指的是文件名而不是模型名。
eg:
例如:
const userModel = mongoose.model("user", userSchema);
const userModel = mongoose.model("user", userSchema);
We should refer to 'user' (model name) instead of 'User' (file name);
我们应该引用“用户”(模型名称)而不是“用户”(文件名);
回答by Visv M
.\nodeapp\node_modules\mongoose\lib\index.js:452
throw new mongoose.Error.MissingSchemaError(name);
^
MissingSchemaError: Schema hasn't been registered for model "users".
Use mongoose.model(name, schema)
at new MissingSchemaError
I got this error resolved when use setTimeout on server.js
我在 server.js 上使用 setTimeout 时解决了这个错误
mongoose.connect(env.get('mongodb.uri'), { useNewUrlParser: true })
.then(() => logger.info("MongoDB successfully connected"))
.catch(err => logger.error(err));
app.use(passport.initialize());
setTimeout(function() {
require("./src/utils/passport")(passport);
}, 3000);
回答by Drumil
Refer the same name that you refer in model name while creating new model.
在创建新模型时引用与您在模型名称中引用的名称相同的名称。
For example: if I have mongoose model like:
例如:如果我有猫鼬模型,如:
var Post = mongoose.model("post",postSchema);
Then I have to refer to posts collection via writing ref:"post".
然后我必须通过写作参考帖子集合ref:"post"。
回答by Nikhil Vats
Here's https://mongoosejs.com/docs/populate.html#cross-db-populate
这是https://mongoosejs.com/docs/populate.html#cross-db-populate
It says we have to pass the model as a third argument.
它说我们必须将模型作为第三个参数传递。
For e.g.
例如
//Require User Model
const UserModel = require('./../models/User');
//Require Post Model
const PostModel = require('./../models/Post');
const posts = await PostModel.find({})
.select('-__v')
.populate({
path: 'user',
select: 'name -_id',
model: UserModel
});
//or
const posts = await PostModel.find({})
.select('-__v')
.populate('user','name', UserModel);
回答by HSP
I also facing same issue but i resolved by removing module.exports
我也面临同样的问题,但我通过删除module.exports解决了
module.exports = mongoose.model('user', userSchema); // remove module.exports
and use like:: mongoose.model('user', userSchema);
module.exports = mongoose.model('user', userSchema); // 移除 module.exports并使用 like::mongoose.model
('user', userSchema);
const mongoose = require('mongoose');
const ObjectId = require('mongoose').ObjectId;
var userSchema = new mongoose.Schema({
Password: { type: String },
Email: { type: String, required: 'This field is required.', unique:true },
songs: [{ type: ObjectId, ref: 'Songs'}]
});
// Custom validation for email
userSchema.path('Email').validate((val) => {
emailRegex = /^(([^<>()\[\]\.,;:\s@"]+(\.[^<>()\[\]\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return emailRegex.test(val);
}, 'Invalid e-mail.');
// module.exports = mongoose.model('user', userSchema); // remove 'module.exports ='
mongoose.model('user', userSchema); // resolved issue
回答by ajay
The issue is with the refs, always make sure to refer the refs to whatever name your are exporting from the models.
问题在于 refs,请始终确保将 refs 引用到您从模型中导出的任何名称。
// Model
// 模型
const Task = mongoose.model('**Tasks**', taskSchema);
//Refs
//引用
userSchema.virtual('tasks', {
ref: '**Tasks**',
localField: '_id', // field in current model
foreignField: 'owner' // corresponding field in other model
});
});

