Mongoose 通过嵌套模型对象进行搜索

问题描述 投票:0回答:1

我有某种产品过滤逻辑。

在产品模型中,我通过查询参数搜索某些产品,如果存在此类过滤,这些参数将被推送到设置数组(queryConditions)中

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

 {
            "_id": "660e867f26ef1583ee426c33",
            "name": "Iphone 15 pro max",
            "__t": "Phones",
            "price": "112000",
            "color": "Black",
            "memory": "128",
            "screen": "2480 x 1080",
            "fps": "240",
            "sim": "eSim",
            "preview": "cf4ab252-e117-4916-a1ee-d8c0db8b72d3.png",
            "images": [
                "6cb510fe-28ca-4ab0-8507-6e8139f05993.png",
                "9806ba4a-3484-43f1-a1dd-acc1d30e9f79.png",
                "a6e59955-05a5-4ce7-99d9-d88394c362ae.png",
                "3ceb7248-d094-47d6-887e-99df40e67d4d.png"
            ],
            "category": {
                "_id": "660c892cb65f2f1f584144ca",
                "name": "Phones",
                "preview": "phone.png"
            },
            "count": 1,
            "__v": 0
        },

过滤逻辑

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

        const queryConditions = []

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

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

        if (category) {
            queryConditions.push({ 'category._id': category })
        }

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

        const length = products.length

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

产品架构

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)

按搜索名称和颜色进行过滤工作正常,但是当我尝试获取其类别等于我通过查询传递的类别的对象时,我得到一个空数组。

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

javascript mongodb express mongoose
1个回答
0
投票

您的 category._id 查询参数可能没有

查询转换
。您可以通过创建
mongoose.Types.ObjectId
的新实例来克服这个问题,如下所示:

if(category){
   queryConditions.push({ 'category._id': new mongoose.Types.ObjectId(category) })
}
© www.soinside.com 2019 - 2024. All rights reserved.