为什么我们必须在猫鼬模型的末尾命名集合
Why do we have to name the collection at the end of a mongoose model
我不明白为什么我可以使用这个访问我的模型:
module.exports = function(mongoose) {
var collection = 'news';
var NewsSchema = new mongoose.Schema({
type: String,
content: String,
img: String,
date: {type: Date, default: Date.now }
});
return mongoose.model(collection, NewsSchema);
}
但我必须指定名称集合才能访问此模型:
module.exports = function(mongoose) {
var collection = 'console';
var ConsoleSchema = new mongoose.Schema({
value: String,
label: String
}, { collection: collection });
return mongoose.model(collection, ConsoleSchema);
}
我使用
访问我的数据
models.news.find({});
models.collection.find({});
我不懂技巧...
谢谢
这是因为 Mongoose 使用模型名称的小写复数版本作为基础集合的默认名称。
所以 'news'
映射到 'news'
(因为它已经是复数),但是 'console'
映射到 'consoles'
,所以你需要使用collection
架构选项。
也可以使用第三个参数设置集合名称为mongoose.model
:
return mongoose.model(collection, ConsoleSchema, collection);
我不明白为什么我可以使用这个访问我的模型:
module.exports = function(mongoose) {
var collection = 'news';
var NewsSchema = new mongoose.Schema({
type: String,
content: String,
img: String,
date: {type: Date, default: Date.now }
});
return mongoose.model(collection, NewsSchema);
}
但我必须指定名称集合才能访问此模型:
module.exports = function(mongoose) {
var collection = 'console';
var ConsoleSchema = new mongoose.Schema({
value: String,
label: String
}, { collection: collection });
return mongoose.model(collection, ConsoleSchema);
}
我使用
访问我的数据models.news.find({});
models.collection.find({});
我不懂技巧...
谢谢
这是因为 Mongoose 使用模型名称的小写复数版本作为基础集合的默认名称。
所以 'news'
映射到 'news'
(因为它已经是复数),但是 'console'
映射到 'consoles'
,所以你需要使用collection
架构选项。
也可以使用第三个参数设置集合名称为mongoose.model
:
return mongoose.model(collection, ConsoleSchema, collection);