【问题标题】:Mongoose: CastError: Cast to ObjectId failed for value "" at path "_id" for model ""Mongoose:CastError:对于模型“”的路径“_id”处的值“”,转换为 ObjectId 失败
【发布时间】:2020-05-11 10:27:37
【问题描述】:

我正在尝试使用 mongodb 和 nodejs 制作应用程序。我制作了一条具有:id 参数的特殊路线,并且运行良好。

我已经创建了另一个包含product/:category 的获取路线。当我每次收到该错误时向该路由发送请求时:

CastError: Cast to ObjectId failed for value "(here is my req.params.category)" at path "_id" for model "Product"

我的路线是:

// product is my model I called it in top of the file
app.get('product/:category', async (req, res)=>{
    const productByCategory = await product.find({category: req.params.category});
    res.json(productByCategory);
});

当我向上面的路线发出 get 请求时,我得到了那个错误:

CastError: Cast to ObjectId failed for value "(here is my req.params.category)" at path "_id" for model "Product"

我的产品型号是:

const ProductSchema = new mongoose.Schema({
    title:{
        type: String,
        required: true
    },
    description:{
        type: String,
        min: 40,
        required: true
    },
    category:{
        type: String,
        required: true
    },
    price:{
        type: Number,
        required: true
    },
    imageUrl:{
        type: String,
        required: true
    },
    quantity:{
        type: Number,
        required: true
    },
    comments: [{
        type: Object
    }],
    seller: {
        sellerId:{
            type: String,
            required: true
        },
        username:{
            type: String,
            required: true
        },
        shopName:{
            type: String,
            required: true
        },
        category:{
            type: String,
            required: true
        }
    },
    location: {
        type: "String",
        required: true
    },
    date:{
        type: Date,
        default: Date.now
    }
});

我该如何解决这个问题?

【问题讨论】:

  • 你对:_id的溃败是这样的:app.get('product/:_id'?
  • @Valijon 不,我想为类别路由。
  • 请发布所有路线
  • @Valijon 你的代码对我有用。无需发布所有路线。

标签: javascript node.js mongodb mongoose


【解决方案1】:

product/:_idproduct/:category 在路由上下文中是“相同的”...因此,即使您发送 product/:category 请求,服务器也会计算匹配的第一个端点。

解决方案 1: 让每条路线独一无二

// _id
app.get('product/_id/:_id', async (req, res)=>{
    const productById = await product.find({_id: req.params._id});
    res.json(productById);
});

// category
app.get('product/category/:category', async (req, res)=>{
    const productByCategory = await product.find({category: req.params.category});
    res.json(productByCategory);
});

...

解决方案2:使用request.body

app.post('product', async (req, res)=>{
    const product = await product.find(req.body});
    res.json(product);
});

注意:注意 NoSQL 注入。

https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/NoSQL%20Injection

【讨论】:

    猜你喜欢
    • 2021-03-13
    • 1970-01-01
    • 2013-06-17
    • 2021-05-12
    • 2019-06-26
    • 2023-03-28
    • 2020-10-19
    • 2017-05-23
    • 2018-07-10
    相关资源
    最近更新 更多