首页 > 解决方案 > Nodejs,Mongodb过滤对象数组的子数组

问题描述

大家好,我有一个包含一些填充字段的对象数组。这是产品的架构。

import mongoose, { Schema } from 'mongoose';

const productSchema = new mongoose.Schema(
  {
    name: String,
    description: String,
    sku: String,
    barcode: String,
    isActive: Boolean,
    quantity: Number,
    availability: String,
    taxClass: [{ type: Schema.Types.ObjectId, ref: 'TaxClass' }],
    images: [{ type: Schema.Types.ObjectId, ref: 'Image' }],
    variants: [{ type: Schema.Types.ObjectId, ref: 'Variant' }],
    tags: [{ type: Schema.Types.ObjectId, ref: 'Tag' }],
    price: {
      comparePrice: Number,
      price: Number
    },
    seo: {
      name: String,
      keywords: [
        {
          name: String
        }
      ],
      description: String,
      image: String
    }
  },
  { timestamps: true }
);

const Product = mongoose.model('Product', productSchema);
export default Product;

所以我有一个功能,我想返回所有具有绿色变体颜色的产品。

export const returnFilteredProducts = async (_, { filters = null, page = 1, limit = 20 }, context) => {
  await jwtAuthentication.verifyTokenMiddleware(context);

  try {
    let searchQuery = {};

    const products = await Product.find(searchQuery).populate(['variants', 'tags', 'images', 'taxClass']);

    console.log(products.filter((item) => item.variants.filter((e) => e.color.indexOf('green') >= 0)));

    return {
      products
    };
  } catch (error) {
    handleError(error);
  }
};

问题是它不会返回带有绿色变体的文档,而是返回所有文档。

我正在实现一个过滤系统,所以我不会在前端使用 redux 过滤产品。

标签: javascriptnode.jsmongodb

解决方案


关于应用于 products 数组的过滤方法:

products.filter((item) => item.variants.filter((e) => e.color.indexOf('green') >= 0))

内部调用 item.variants.filter() 返回一个数组。

外部调用: products.filter() 将包含产品项,因为数组将强制为真,即使为空也是如此。

您可以使用方法Array.some()进行内部调用,如果 item.variants 中的至少一项 (e) 具有所需的颜色,它将返回布尔值 true。

这样,您将在 item.variants 数组的至少一个元素中过滤掉所有不包含所需颜色的产品项目。


推荐阅读