我有某种产品过滤逻辑.

在Products模型中,我通过查询参数搜索某些产品,如果存在这样的过滤,则这些参数被推入设置数组(queryConditions)中

这是产品模型中存在的对象之一

{
    "products": [
        {
            "_id": "6612fee192f83be6c8f1f14a",
            "name": "Iphone 15",
            "__t": "Phones",
            "price": "105990",
            "color": "Белый",
            "memory": "128",
            "screen": "2480 x 1080",
            "fps": "240",
            "sim": "eSim",
            "preview": "3e26f117-e925-4303-adb5-930874e7ea21.png",
            "images": [
                "3db588ef-63f6-4596-8284-f02f4e465765.png",
                "e9437348-eb56-4537-8c13-cbbb697bcc41.png"
            ],
            "category": {
                "_id": "6612b3c9a56d07ad6a21e332",
                "name": "Телефоны",
                "preview": "phones.png"
            },
            "type": "6612b4a9a56d07ad6a21e384",
            "count": 1,
            "createdAt": "2024-04-07T20:15:29.009Z",
            "updatedAt": "2024-04-07T20:15:29.009Z",
            "__v": 0
        }
    ],
    "count": 1
}

滤波逻辑

import { mongoose } from 'mongoose'
import ProductsModel from '../models/ProductsModel.js'

class ProductsController {
    async getAll(req, res) {
        // Filters
        const { search, color, date, category, price } = req.query
        const limit = 10
        const page = Number(req.query.page) || 1
        const skip = (page - 1) * limit

        const queryConditions = []
        const sortConditions = []

        if (search) {
            queryConditions.push({ name: new RegExp(search, 'i') })
        }

        if (color) {
            queryConditions.push({ color: color })
        }

        if (category) {
            // queryConditions.push({ type: new mongoose.Types.ObjectId(category) })
            queryConditions.push({ 'category._id': new mongoose.Types.ObjectId(category) })
        }

        console.log(category)

        if (price === 'up') {
            sortConditions.push(['price', 1])
        }

        if (price === 'down') {
            sortConditions.push(['price', -1])
        }

        if (date === 'old') {
            sortConditions.push(['createdAt', 1])
        }

        if (date === 'new') {
            sortConditions.push(['createdAt', -1])
        }

        const products = await ProductsModel.find()
            .populate({ path: 'category', select: ['name', 'preview'] })
            .and(queryConditions.length > 0 ? queryConditions : [{}])
            .sort(sortConditions)
        // .skip(skip)
        // .limit(limit)

        const count = await ProductsModel.find()
            .and(queryConditions.length > 0 ? queryConditions : [{}])
            .countDocuments()

        return res.json({ products, count })
    }

export default new ProductsController()

产品方案

import { Schema, model } from 'mongoose'

export const productsDiscriminatorKey = 'productKind'

const ProductsSchema = new Schema(
    {
        name: { type: String },
    },
    { productsDiscriminatorKey, timestamps: true }
)

export default model('Products', ProductsSchema)

类别计划

import { Schema, model } from 'mongoose'

const CategoryModel = new Schema(
    {
        name: {
            type: String,
            required: true,
            unique: true,
        },
        preview: {
            type: String,
            required: true,
        },
        types: [{ type: Object }],
    },
    { timestamps: true }
)

export default new model('Category', CategoryModel)

电话架构

import mongoose, { Schema } from 'mongoose'

import ProductsModel, { productsDiscriminatorKey } from './ProductsModel.js'

const PhoneSchema = new Schema(
    {
        name: { type: String, required: true },
        price: { type: String, required: true },
        color: { type: String, required: true },
        memory: { type: String, required: true },
        screen: { type: String, required: true },
        fps: { type: String, required: true },
        sim: { type: String, required: true },
        preview: { type: String, required: true },
        images: [{ type: String, required: true }],
        category: {
            type: mongoose.Schema.ObjectId,
            ref: 'Category',
        },
        type: {
            type: mongoose.Schema.ObjectId,
            ref: 'Type',
        },
        count: { type: Number },
    },
    { productsDiscriminatorKey }
)

const PhoneModel = ProductsModel.discriminator('Phones', PhoneSchema)
export default PhoneModel

通过搜索名称和 colored颜色 进行过滤是正确的,但是当我试图获取一个类别等于我通过查询传递的类别的对象时,我得到了一个空array.

实际上,问题是如何正确地实现对嵌套类别对象的搜索,并获得类别ID对应于我通过查询传递的ID的对象,

推荐答案

很可能您的category._id查询参数没有Query Casting.你可以通过创建一个新的mongoose.Types.ObjectId实例来克服这个问题,如下所示:

if(category){
   queryConditions.push({ 'category': new mongoose.Types.ObjectId(category) })
}

Javascript相关问答推荐

如何在加载的元数据上使用juserc和await中获得同步负载?

React对话框模式在用户单击预期按钮之前出现

在JavaScript中,是否有一种方法可以创建自定义thable,在等待某些代码后自动触发它?

foreach循环中的Typescript字符串索引

React Native平面列表自动滚动

如何使用JavaScript用等效的功能性HTML替换标记URL格式?

fs. writeFile()vs fs.writeFile()vs fs.appendFile()

Google Apps脚本中的discord邀请API响应的日期解析问题

. NET中Unix时间转换为日期时间的奇怪行为

JQuery. show()工作,但. hide()不工作

如何从Intl.DateTimeFormat中仅获取时区名称?

使用LocaleCompare()进行排序时,首先使用大写字母

如何通过将实例方法的名称传递给具有正确类型的参数的继承方法来调用实例方法?

为什么JPG图像不能在VITE中导入以进行react ?

MongoDB受困于太多的数据

expo 联系人:如果联系人的状态被拒绝,则请求访问联系人的权限

AG-GRIDreact 显示布尔值而不是复选框

bootstrap S JS赢得了REACT中的函数/加载

对不同目录中的Angular material 表列进行排序

通过ng-绑定-html使用插入的HTML中的函数