使用Postman发送GET请求以获取对象数组

时间:2018-09-11 07:26:48

标签: arrays node.js mongoose

我正在尝试为我的节点其余API发送GET请求,该API由“产品子类别”的对象数组组成。我被困在如何实现这一目标上。这是我的产品架构及其子类别:

    const subSchema = mongoose.Schema({
    tshirt: {
      type: Boolean,
    },

    mobile: {
        type: Boolean,

    },
    laptop: {
        type: Boolean,

    },

  });


const productSchema = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    name: { type: String, },
    price: { type: Number, },
    quantity: { type: Number, },
    mainCategory: { type: String, },
    subCategory: [subSchema]

});

这就是我定义“控制器”以通过SubCategory提取产品的方式:

  exports.products_get_bySubCategory = (req, res, next) => {
  Product
  .find({subCategory: req.params.subCategory })
  .exec()
  .then(docs => {
    const response = {
      count: docs.length,
      products: docs
    };
    res.status(200).json(response);
  })
  .catch(err => {
    console.log(err);
    res.status(500).json({
      error: err
    });
  });
};

这就是我尝试通过URL访问产品的方式:

http://localhost:5000/products/subCategory/

请帮助我实现按类别获取产品的正确方法。

sample data image

1 个答案:

答案 0 :(得分:0)

根据示例数据,您提供了解决问题的方法,如下所示:

//based on the sample: { "upperwearKey" : "upperwearValue" }
var alternativeFilter  = { subCategory:  { "$elemMatch": { upperwearKey : "upperwearValue", anotherKey: "anotherValue" } } }; //alternative with "$elemMatch"
var filter = { "subCategory.upperwearKey": "upperwearValue" }; 
    Product.find(filter)//you can also use ´alternativeFilter´ 
    .exec()
    .then(docs => {
        const response = {
        count: docs.length,
        products: docs
        };
        console.log(response);
    })
    .catch(err => {
        console.log(err);      
    });