Schema尚未注册模型。 MongoDB的>猫鼬

问题描述 投票:3回答:1

您好我的代码如下所示:

var mongoose=require('mongoose');
mongoose.connect('mongodb://localhost/test');

var Schema=mongoose.Schema
, ObjectId=Schema.ObjectId;

var BlogPost= new Schema({
    author:ObjectId,
    title:String,
    body:String,
    date:Date
    });

var myModel =mongoose.model('BlogPost','BlogPost');
console.log(myModel);

需要建议。我总是得到这个例外。

  500 MissingSchemaError: Schema hasn't been registered for model "BlogPost".<br/>Use mongoose.model(name, schema)
node.js mongodb mongoose
1个回答
8
投票

你以错误的方式打电话给mongoose.model。您应该传递一个架构对象对象,但是您要传递'BlogPost'字符串。请尝试以下代码:

var BlogPost= new Schema({
  author: ObjectId,
  title: String,
  body: String,
  date: Date
});

var myModel = mongoose.model('BlogPost', BlogPost); // BlogPost is an object here

之后,mongoose将在blogposts数据库中创建mongodb://localhost/test集合(小写和复数)。如果要更改与模型对应的集合名称,请将其作为thirs参数传递:

var myModel = mongoose.model('BlogPost', BlogPost, 'BlogPost');
© www.soinside.com 2019 - 2024. All rights reserved.