【问题标题】:Mongoose populate with match condition for nested documentMongoose 填充嵌套文档的匹配条件
【发布时间】:2023-03-26 08:41:01
【问题描述】:

我有一个像这样的猫鼬模式:

var Address = {
    doorNo:String,
    city:String,
    state:String,
    country:String,
    district:String,
    zipCode:String,
    area:String,
    locality:String
};

var StoreSchema = {
    name:String,
    address:Address,
    category:[String],
    products:[{ type:Schema.ObjectId, ref:"Product" }], 
};

var ProductSchema = {
    name:String,
    description:String,
    category:String,
    subCategory:String,
    store: { type:Schema.ObjectId, ref:"Store", childPath:"products" }
};

我需要根据产品类别和地址城市过滤产品。仅获取属于特定位置(地址架构中的城市)和特定类别的产品。

我尝试了以下代码:

Product
  .find({'category':'accessories'})
  .populate({
    path: 'store',
    match: { 'address.city': req.params.location},
    select:'_id'

})

现在这将返回所有类别匹配但位置过滤器不满足的产品,它返回一个带有 null 的商店,并在满足位置过滤器的地方返回商店。

【问题讨论】:

    标签: mongoose-populate


    【解决方案1】:

    在 Mongoose 5.2.7 中,语法 match: { 'x.y': 'something' } 用作魅力

    【讨论】:

    • 你能给出这个语法的完整例子吗?你打电话给哪个populate,model 还是文档?哪些选项类型、位置或对象?
    【解决方案2】:

    也许你可以试试这个,它对我有用。

    Product
      .find({ category: 'accessories' })
      .populate({
        path: 'store', 
        model: 'Store', 
        match: {
          address.city: { $eq: 'YOUR_CITY' }
        }
      })
      .exec(function (err, res){})
    

    【讨论】:

    • 当它甚至不是有效的语法before我编辑它时,它是如何为你工作的?
    【解决方案3】:

    在此处的文档中说明:https://mongoosejs.com/docs/populate.html#query-conditions

    解决办法应该是:

    Product
      .find({...})
      .populate({
        ...
        match: { 'city': req.params.location},
        ...
    })
    

    你不需要'address.city' 只需match: { 'city': req.params.location}

    【讨论】:

      猜你喜欢
      • 2012-04-16
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 2014-08-06
      • 2015-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多