Mongoose Schema尚未注册模型

时间:2014-11-08 14:23:59

标签: node.js mongodb mongoose

我正在学习平均堆栈,当我尝试使用

启动服务器时
npm start

我得到一个例外说:

schema hasn't been registered for model 'Post'. Use mongoose.model(name, schema)

这是我在/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);

因为我可以看到应该为模型'Post'注册模式,但是什么可能导致抛出异常?

提前致谢。

编辑:这是异常错误

/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)

这是使用mongoose初始化的app.js代码:

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/news');
require('./models/Posts');
require('./models/Comments');

行之前:

app.use('/', routes);

18 个答案:

答案 0 :(得分:108)

这不是模型导出的问题。我遇到过同样的问题。

真正的问题是模型的需要声明

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/news');
require('./models/Posts');
require('./models/Comments');

低于路由依赖项。只需将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();

答案 1 :(得分:19)

如果某人无法通过正确答案的方法(像我一样)修复它,请尝试查看模式的创建。我将'ref'写成'User',但正确的是'user'。

<强>错误:

createdBy: {
    type: Schema.Types.ObjectId,
    ref: 'User'
}

<强>正确:

createdBy: {
    type: Schema.Types.ObjectId,
    ref: 'user'
}

答案 2 :(得分:14)

如果您使用多个mongoDB连接

请注意,当使用.populate()时,你必须提供模型,因为mongoose只会&#34;找到&#34;同一连接上的模型。 即在哪里:

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

<强>正确:

Customer.findOne({}).populate('created_by', 'name email', User)

Customer.findOne({}).populate({ path: 'created_by', model: User })

不正确(生成&#34;架构尚未注册模型&#34;错误):

Customer.findOne({}).populate('created_by');

答案 3 :(得分:1)

当您使用的模型依赖于另一个模型,但该模型尚未注册时,就会发生此问题。

一个简单的解决方法是 将 model 添加到 popualte 而不是依赖于架构中的 ref

=>> 示例

const jobs = await Job.find({}).populate({
    path: "jobDescriptions",
    model: JobDesc,
    select: "list",
    populate: {
      path: "list",
      select:"name list",
      model: Skill,
    },
  });

答案 4 :(得分:1)

我也面临着同样的问题。 解决我的问题的方法是查看ref参数,该参数与我实际导出的模型相比具有不同的名称,因此找不到此类模型。

userSchema.virtual('tasks', {
    ref: 'Task',
    localField: '_id',
    foreignField: 'owner'
})
  

我实际导出的是:-

const Tasks = mongoose.model('Tasks', taskSchema)

module.exports = Tasks

Task纠正为Tasks后,我的问题得到解决

答案 5 :(得分:1)

我使用以下方法解决了问题

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

请注意,这里ref没有string类型值,现在它是指Comment模式。

答案 6 :(得分:1)

.\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

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

答案 7 :(得分:0)

就我而言,此问题是因为我没有在应用程序中包括模型或ref模型。 因此,您应该在节点应用程序中需要Post modelComment model

答案 8 :(得分:0)

当我们在猫鼬模型之间创建错误的引用(ref)时,也会弹出此错误。

就我而言,我指的是文件名而不是型号名。

例如:

const userModel = mongoose.model(“ user”,userSchema);

我们应该使用“用户”(型号名称)而不是“用户”(文件名称);

答案 9 :(得分:0)

在创建新模型时,请参考在模型名称中引用的相同名称。

例如:如果我有猫鼬模型,例如:

var Post = mongoose.model("post",postSchema);

然后,我必须通过撰写ref:"post"来引用帖子集合。

答案 10 :(得分:0)

这里是https://mongoosejs.com/docs/populate.html#cross-db-populate

它说我们必须将模型作为第三个参数传递。

例如

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

答案 11 :(得分:0)

我也面临同样的问题,但我通过删除 module.exports

解决了
  

module.exports = mongoose.model('user',userSchema); //删除module.exports
  并使用如下形式: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

答案 12 :(得分:0)

问题出在引用上,始终确保将引用引用到您要从模型中导出的任何名称。

//型号

const Task = mongoose.model('**Tasks**', taskSchema);

//参考

userSchema.virtual('tasks', {
ref: '**Tasks**',
localField: '_id', // field in current model
foreignField: 'owner' // corresponding field in other model

});

答案 13 :(得分:0)

我的问题是使用以下方法解决的

adminModel.findById(req.params.id).populate({ 路径:“用户”, 模型:userModel //用户集合名称 })

答案 14 :(得分:0)

您还应检查数据库中是否存在脏数据。我最终得到的文档包含引用模型的小写版本(user而不是User)。这会导致错误并且非常难以追踪。

使用快速mongo查询轻松修复:

db.model.updateMany({ approvedByKind: 'user' }, { $set: { approvedByKind: 'User' } })

答案 15 :(得分:0)

只是想为我补充一点,在导入导致失败的Schema时,我正在使用解构。

正确

var intakeSchema = require('../config/models/intake')

不正确

var { intakeSchema } = require('../config/models/intake')

答案 16 :(得分:0)

您没有给模型任何价值

就我而言,我使用的模型在建立MongoDB连接时并未对其进行更新。

所以,我有类似的东西

const Device = require('../../models/device')
// make use of Device

与此连接

conn = await mongo.createConnection(conn,
      [JobApplication, Job, User])

修复

启动连接时,您必须将模型添加到conn

conn = await mongo.createConnection(conn,
      [JobApplication, Job, User, Device])

请注意,我在连接中添加了Device

答案 17 :(得分:0)

阐述Rafael Grilli的答案,

正确:

var HouseSchema = new mongoose.Schema({
  date: {type: Date, default:Date.now},
  floorplan: String,
  name:String,
  house_id:String,
  addressLine1:String,
  addressLine2:String,
  city:String,
  postCode:String,
  _locks:[{type: Schema.Types.ObjectId, ref: 'xxx'}] //ref here refers to the first parameter passed into mongoose.model()
});
var House = mongoose.model('xxx', HouseSchema, 'houseschemas');