【问题标题】:Mongoose populate with filter猫鼬填充过滤器
【发布时间】:2020-06-01 20:54:25
【问题描述】:

我的架构:

const ProductSchema = new Schema({
    Category: String,
    Subcategory: String,
    Name: String,
    Offers: [{ type: ObjectId, ref: "Offer" }]
})

const OfferSchema = new Schema({
    Quantity: Number,
    Images: [String],
    Price: Number,
    Size: String,
    Color: String
})

我正在查询带有限制和跳过的过滤器优惠的产品。我试过这个:

const products = await ProductSchema.find({ ...someFilter }).populate({
    path: "Offers",
    match: {
        Quantity: { $gt: 2 },
        Images: { $exists: true, $ne: [] }
    }
}).skip(skip).limit(limit)

而且我只想获取报价长度> 0 的文档。但我得到的文档为空报价。如果我这样过滤:

products.filter(item => item.Offers.length > 0)

我的分页会中断。你能帮助我吗?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    只要求Offers 字段不能像这样为空:

    const products = await ProductSchema.find(
        {
            ...someFilter,
            "Offers.0": {$exists: true}
        }
    ).populate({
        path: "Offers",
        match: {
            Quantity: {$gt: 2},
            Images: {$exists: true, $ne: []}
        }
    }).skip(skip).limit(limit)
    

    【讨论】:

    • 已经很接近了,但是商品的图片可能是空数组,所以我不需要它们。
    • 那么我建议您在image_count 之类的文档上创建一个新字段并匹配image_count > 0。在 1 db 命令中执行此操作的唯一方法是使用 aggregate,这对于 padgination 的性能非常糟糕,因为您必须在使用 skip 和 limit 之前查找整个集合。
    • 所以我想,我必须将 image_count 添加到 Offers 中?但这将是同样的事情。
    猜你喜欢
    • 2019-12-21
    • 2021-11-07
    • 2015-07-13
    • 2016-10-10
    • 2019-09-16
    • 2021-12-25
    • 2015-07-13
    • 2020-01-17
    相关资源
    最近更新 更多