首页 > 解决方案 > 在 Node.js 和 MongoDB 中无法通过此查询获得所有信息

问题描述

我正在尝试为我的 api 创建一条路线,以返回商店中的所有商品,但仅限于 url 参数中给出的类别。

但是在邮递员中使用路线时出现此错误

Cast to ObjectId failed for value "shirt" at path "_id" for model "clothes"

这是代码,我使用的是 node.js、express 和 mongoose。

//GET ALL BY CATEGORY

router.get('/:category', async (req, res)=>{
  try{
    const categoryClothes = await Clothes.find(
      {type:req.params.category  })
      res.send(categoryClothes)
  }
  catch(err){
    console.log(err.message)
  }
})

猫鼬模式

const Clothes = mongoose.model('clothes', new mongoose.Schema({
  price: Number,
  name:{
    type: String,
    lowercase: true,
    required: true
  },
  size: {
    type: Array,
    lowercase: true
  },
  picture: {
    type:String,
    required:true
  },
  footsize:{
    type: Array
  },
  type:{
    type: String,
    enum:['jacket', 'sneaker', 'hat', 'shirt', 'pants'],
    lowercase: true,
    required: true

  }, 
  sex:{
    type: String,
    enum: ['m', 'f', 'unisex'],
    lowercase: true,
    required: true
  }
}))

标签: node.jsmongodbexpressmongoosebackend

解决方案


问题是我在这条路线之前有一条路线,它有 /:id 并且它总是进入那里并试图在 _id 中找到类别。

我的解决方案是在 /:id 之前移动 /:category 路由

但是,如果有人可以向我解释发生这种情况的原因,我将不胜感激。


推荐阅读