【问题标题】:How to pass nested fields in a REST API link to filter mongoose nested models如何在 REST API 链接中传递嵌套字段以过滤猫鼬嵌套模型
【发布时间】:2019-04-11 05:51:05
【问题描述】:

我正在开发一个 REST API,但我不知道如何使用 productType.markteplace.name 的嵌套字段进行过滤。

以下是模型:

hashtag : {
    name: {type: String },
    productType: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'ProductType',
      required: true
    }
}
productType:  {
    name: {type: String},
    marketplace: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Marketplace'
    }
  }

这是搜索的Controller

    let options = {
      populate: [{
        path: 'supplier',
        model: Supplier
      },
      {
        path: 'productType',
        model: ProductType,
        populate: {
          path: 'marketplace',
          model: Marketplace
        }
      }]
    };
    let search = { };
    if (req.query.search) {
      search.name = req.query.search;
    }
    let conditions = {
      ...req.query.conditions,
      ...search
    };
    Hashtag.paginate(conditions, options).then((result) => {
      res.status(200).json(result);
    })

使用此代码,普通过滤器或像“&name=x”这样的搜索可以正常工作,但我问的是如何使用市场名称“&productType.markteplace.name=x”的值进行过滤

【问题讨论】:

    标签: javascript node.js rest mongoose


    【解决方案1】:

    使用find(),您可以填充所有集合,然后遍历文档。

    Hashtag.find({})
      .populate({
            path: 'productType',
            model: ProductType,
            populate: {
              path: 'marketplace',
              model: Marketplace
            }
          })
      .then(function(hashtags) {
        hashtags.find(hashtag => hashtag.productType.marketplace.name == req.query.search)
      })
      .catch(err => console.log(err));
    

    【讨论】:

      猜你喜欢
      • 2021-11-07
      • 2018-06-23
      • 2020-06-04
      • 2013-10-07
      • 2013-07-21
      • 2021-12-25
      • 1970-01-01
      • 2019-03-22
      • 2020-11-05
      相关资源
      最近更新 更多