【问题标题】:Impossible to query nested mongoose array?无法查询嵌套的猫鼬数组?
【发布时间】:2021-08-08 15:53:14
【问题描述】:

我想在内部使用正则表达式和猫鼬(mongoDB)模型进行查询和数组。

我想在 Productmodel 的嵌套数组中搜索:

const productSchema = new schema(
  {
    name: requiredString,
    sku: requiredUniqueNumber,
    ean: requiredUniqueNumber,
    suppliers: [{ type: mongoose.Schema.Types.ObjectId, ref: SupplierModel }],
    categories: [{ type: mongoose.Schema.Types.ObjectId, ref: CategoryModel }],
    mainImage: requiredString,
    images: [{ type: String }],
    description: requiredString,
    stock: requiredNumber,
    price: requiredNumber,
    totalOrders: requiredNumber,
    reviews: [review],
  },
  {
    timestamps: true,
    count: true,
  }
);

“供应商”数组中的模型是:

const supplierSchema = new schema(
  {
    supplierName: requiredUniqueString,
    invoiceAddress: address,
    visitAddress: address,
    status: supplierStatusEnum,
    contacts: address,
    accountType: accountTypeEnum,
    logo: requiredString,
    user: { type: schema.Types.ObjectId, ref: "products" },
  },
  {
    timestamps: true,
  }
);

现在问题来了,如果我查询和populate(),我会得到所有结果。但由于某种原因,我无法在包含多个供应商的数组中搜索。这是我所拥有的:

 foundProducts = await ProductModel.find({
          $or: [
            {
              name: {
                $regex: regex,
              },
            },
            {
              "suppliers.supplierName": {
                $regex: regex,
              },
            },
            {
              description: {
                $regex: regex,
              },
            },
          ],
        });

JSON 中的对象:

如果他发现供应商模型包含正则表达式,他应该返回包含该供应商的整个产品模型。

在嵌套数组中的所有项目中搜索的最佳方法是什么。

ps。我是一名来自 PostgreSQL 的初级开发人员,所以在我尝试这个 noSQL“东西”时对我很赤裸裸:)

【问题讨论】:

    标签: javascript arrays mongodb mongoose mongoose-populate


    【解决方案1】:

    我做错了查询。我需要做的

    {
       "suppliers._id": {
           $regex: regex,
       },
    },
    

    我只能搜索_id,因为这是我“建模”它的方式。

    【讨论】:

      猜你喜欢
      • 2021-03-23
      • 2019-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-17
      • 2018-02-02
      • 1970-01-01
      相关资源
      最近更新 更多