【问题标题】:Is it possible to query a mongoose model using a text field in an associated model?是否可以使用关联模型中的文本字段查询猫鼬模型?
【发布时间】:2022-02-20 06:34:13
【问题描述】:

我有两个猫鼬模型,它们的关系如下:

const ProductSchema: Schema = new Schema(
{
    name: String,
    category: {
        type: Schema.Types.ObjectId,
        ref: 'Category'
    },
    description: String
}

namedescription 字段上有一个文本索引。

类别架构如下所示

const CategorySchema: Schema = new Schema(
{
    title: String
}

title 字段上有文本索引。

是否可以对产品进行全文搜索,例如关键字可以包含类别标题,甚至可以仅使用类别标题进行文本搜索?

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    您可以找到所有产品,填充它们,然后使用.filter() 过滤。

    代码看起来像这样(我猜你知道如何收集用户输入,所以我跳过了那部分):

    // If you have saved the user input in a variable
    const searchFieldInput = "foo";
    
    const products = await Product
      .find({}) // Finds all Products in the DB
      .populate("category"); // Populates the Category field
    
    // Filter the products array based on the user input
    const filteredProducts = products.filter((product) =>
      product.category.includes(searchFieldInput)
    )
    

    【讨论】:

      猜你喜欢
      • 2013-07-15
      • 1970-01-01
      • 2015-10-21
      • 1970-01-01
      • 2020-06-29
      • 1970-01-01
      • 2014-02-15
      • 2021-09-19
      • 1970-01-01
      相关资源
      最近更新 更多