【问题标题】:Mongoose .find() returns an empty array when searching by enum fieldMongoose .find() 通过枚举字段搜索时返回一个空数组
【发布时间】:2022-01-21 04:49:22
【问题描述】:

我有这个架构:

const SoundSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    minFrec: {
        type: Number,
        required: true
    },
    maxFrec:{
        type: Number,
        required: true
    },
    minInt:{
        type: Number,
        required: true
    },
    maxInt:{
        type: Number,
        required: true
    },
    category: {
        type: String,
        lowercase: true,
        required: true,
        enum: ["Hogar", "Naturaleza", "Conversación", "Ocio", "Lugares", "Ciudad"]
    }
});

我正在尝试创建这条路线来显示我所有与某个类别匹配的项目:

app.get("/sounds/:category", async (req, res) => {
const sounds = await Sound.find({ category: 'Ocio' }).sort({ name: 'asc'});
res.render("sounds/category", { sounds });
});

它不起作用(返回一个空数组),但如果我用没有“枚举”的东西(名称、minInt 等)进行过滤,它就会起作用。

我已经完成了其他可行的路线,我可以在 mongo (db.sounds.find({category: "Ocio"})) 中找到这些项目。

【问题讨论】:

    标签: javascript node.js mongodb express mongoose


    【解决方案1】:

    您的架构将字段 category 定义为 lowercase: true,这意味着字符串将以小写形式保存 (docs)

    因此,您必须在查询中使用小写字母来匹配确切的值。

    const sounds = await Sound.find({ category: 'ocio' }).sort({ name: 'asc'});
    

    或者更全球化的东西:

    const sounds = await Sound.find({ category: req.params.category.toLowerCase() }).sort({ name: 'asc'});
    

    甚至另一个选项是使用$regex 和选项i 就像this example 但考虑到您的架构确保该字段是小写的,这是一个更昂贵的选项。所以使用toLowerCase() 是更好的选择。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-18
      • 2019-10-27
      • 2019-04-27
      • 2017-05-14
      • 1970-01-01
      • 2021-09-16
      相关资源
      最近更新 更多