【问题标题】:Why do we have to name the collection at the end of a mongoose model为什么我们必须在猫鼬模型的末尾命名集合
【发布时间】:2015-06-26 02:26:17
【问题描述】:

我不明白为什么我可以使用这个来访问我的模型:

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({});

我不明白这些技巧......

谢谢

【问题讨论】:

    标签: node.js model mongoose schema


    【解决方案1】:

    这是因为 Mongoose 使用模型名称的小写复数形式作为基础集合的默认名称。

    所以'news' 映射到'news'(因为它已经是复数),但是'console' 映射到'consoles',所以您需要使用架构上的collection 选项显式设置集合名称。

    您也可以使用第三个参数将集合名称设置为mongoose.model

    return mongoose.model(collection, ConsoleSchema, collection);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-19
      • 2022-10-24
      • 2012-01-26
      • 2017-01-04
      • 1970-01-01
      • 1970-01-01
      • 2021-07-06
      相关资源
      最近更新 更多