首页 > 解决方案 > 文本索引 MongoDB 的对象数组

问题描述

我已经浏览了解决方案,但在我的情况下似乎没有一个工作

MongoDB 文本索引数组对象列

在 MongoDB 中索引对象数组

我的问题是我有一个列表猫鼬模型,其中每个列表可以有许多类别,我希望能够通过类别搜索并返回与这些类别关联的所有列表。

我的模型是这样定义的

let ListingSchema = new Schema({
    categories: [{
        id: {type: Number, required: true},
        name: {type: String, required: true},
        suggestedName: {type: String, required: true},
        link: {type: String, path: true}
    }],
    allergyAdvice: {type: String},
    location: {type: String, required: true, maxlength: 100},
    vendorId: {type: Schema.Types.ObjectId, ref: 'User', index: true},
}, {timestamps: true});

ListingSchema.index({
    alergyAdvice: 'text',
    'categories.name': 'text',
}, {
    weights: {
        'categories.name': 7,
        alergyAdvice: 4,
    },
});

ListingSchema.set('toObject', {getters: true});
ListingSchema.set('toJSON', {getters: true});

在搜索具有相关类别的列表时,我使用以下查询 -

const listings = await Listing.find({
                $text: {$search: "Sweet"}
            });

该查询适用于alergyAdvice 索引,但不适用于该索引,categories.name并且会为列表返回一个空数组。

标签: javascriptnode.jsmongodbtypescriptmongoose

解决方案


推荐阅读