【问题标题】:How to perform a part of text search in mongoose array of objects如何在对象的猫鼬数组中执行部分文本搜索
【发布时间】:2018-10-10 00:06:38
【问题描述】:

我有一个架构,我需要在对象数组中执行搜索。我尝试了很多方法,但似乎不起作用。下面是我的代码。

let productsSchema = new mongooseSchema({
    productId: {type: mongooseSchema.Types.ObjectId, ref: 'Product'},
    mainAttributes: [{
        subCategoryId: {type: mongooseSchema.Types.ObjectId, ref: 'CategorySubCategory'},
        attributes: Object
    }],
    createdAt: Date,
    updatedAt: Date
})

productsSchema.index({'mainAttributes': 'text'})

let attributes = mongoose.model('Attributes', productsSchema); 

let results = await CategorySubCategory.attributes.find({"$text": {"$search": req.body.searchText}})

目前以下记录保存在mongodb中

{
    "_id" : ObjectId("5bba1b39ad9387431f9f5fd9"),
    "productId" : ObjectId("5bba1b397d90713320c441f8"),
    "__v" : 0,
    "createdAt" : ISODate("2018-10-07T14:42:01.723Z"),
    "mainAttributes" : [ 
        {
            "_id" : ObjectId("5bba1b397d90713320c441f9"),
            "subCategoryId" : ObjectId("5bba1b397d90713320c441f7"),
            "attributes" : {
                "title" : {
                    "text" : "some title",
                    "type" : "text"
                }
                "state" : {
                    "text" : "California",
                    "type" : "text"
                },
                "city" : {
                    "text" : "San Francisco",
                    "type" : "text"
                }
            }
        }, 
        {
            "_id" : ObjectId("5bba1b397d90713320c441fb"),
            "subCategoryId" : ObjectId("5bba1b397d90713320c441fa"),
            "attributes" : {
                "temprature" : {
                    "degree" : "20C",
                    "type" : "text"
                }
            }
        }
    ],
    "updatedAt" : ISODate("2018-10-07T14:42:01.723Z")
}

我需要根据文本进行搜索,例如当我给 San 时,它应该返回结果,但它返回空。

【问题讨论】:

    标签: node.js mongodb mongoose mongodb-query


    【解决方案1】:

    我已经弄清楚是什么问题了,

    我需要显式删除一个索引,然后添加

    productsSchema.index({'$**': 'text'}) 让它工作

    【讨论】:

      猜你喜欢
      • 2016-05-11
      • 2017-01-14
      • 1970-01-01
      • 2020-02-21
      • 1970-01-01
      • 2020-07-31
      • 1970-01-01
      • 2015-12-28
      • 2021-05-06
      相关资源
      最近更新 更多