javascript - 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 过滤产品。
解决方案
关于应用于 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 数组的至少一个元素中过滤掉所有不包含所需颜色的产品项目。
推荐阅读
- jenkins - Jenkins 声明性管道字符串参数和建议
- reactjs - 当用户与按钮交互时,Redux 回调函数
- mysql - 通配符 LIKE 是否比 MySQL 中的多个布尔搜索更高效?
- php - 使用 CollectionType 时无法保存实体
- ruby - Capybara / RSpec 确保页面上任何地方都不存在某些东西
- html - 有没有办法将“a”标签链接取消设置为默认颜色
- julia - 具有通用函数成员的结构数组?
- heroku - 即使它在 requirements.txt 文件中,Heroku 也不会安装模块 psycopg2
- intellij-idea - IntelliJ PlantUML 插件不检测 *.pu 文件
- ruby-on-rails - 如何通过 application.html.erb 将引导闪存消息添加到整个应用程序?