Skip to content
Advertisement

Impossible to query nested mongoose array?

I want to Query and array with regex inside and mongoose (mongoDB) model.

I want to search inside the nested array of the 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,
  }
);

The model inside the “suppliers” array is:

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,
  }
);

Now here’s the problem, if i query and and populate() i get all the results. But for some reason I cannot search inside the Array containing several suppliers. Here’s of what i have:

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

The object in JSON: enter image description here

If he finds that the suppliers model contains the regex he should give back the whole porductmodel containing that supplier.

What is the best way to search in all the items inside of an nested array.

ps. I’m a junior developer comming from PostgreSQL, so bare with me while I’m trying this noSQL “thing” 🙂

Advertisement

Answer

I was doing the wrong query. I need to do

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

I can only search on _id, since this is the way that i “modeled” it.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement