您好我的代码如下所示:
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)
你以错误的方式打电话给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');