最近,迷上了mongoDB,也抽时间简单看了下文档,还有网上五花八门的教程,什么连接,配置,写控制层,业务层,DAO层等等一堆,但是真正等我自己敲(chao)代码的时候,居然发现数据库是连上了,但是据说没有数据,于是又各种捣鼓,各种百度,原来...
官网原话有这么一个示例,请注意下面一行解释:
Compiling your first model
var schema = new mongoose.Schema({ name: 'string', size: 'string' });
var Tank = mongoose.model('Tank', schema);
The first argument is the singular name of the collection your model is for. Mongoose automatically looks for the plural version of your model name. Thus, for the example above, the model Tank is for the tanks collection in the database. The .model()
function makes a copy of schema
. Make sure that you've added everything you want to schema
before calling .model()
!
翻译过来:大致是
第一个参数是模型所用集合的单数名称。 Mongoose会自动查找您的模型名称的复数版本。 因此,对于上面的示例,模型Tank用于数据库中的tanks集合。 .model()函数生成模式的副本。 在调用.model()之前,请确保已添加了您想要被模型转换的所有字段!
简而言之,就是Mongoose会自动查找您的模型名称的复数版本,比如你的模型定义的是banner,那么数据库中collection对应的名称应该为banners,而不是banner。
// 原来配置model
const BannerModel = mongoose.model('banner', bannerSchema)
两种方法修改:
第一种是:原来配置不变,修改数据库表名(collection)为复数形式;
第二种是:数据库表名(collection)不变,修改配置;
// 制定第三个参数指定表名
const BannerModel = mongoose.model('banner', bannerSchema, 'banner');
这个问题就此告一段落了!!!