mongodb 对于模型\“product\”的路径\"_id\”处的值\“hello\”(类型字符串),转换为ObjectId失败,

icomxhvb  于 2023-10-16  发布在  Go
关注(0)|答案(1)|浏览(125)

我有mongodb本地数据库和im使用节点和express和mongoose。
我做的所有路由工作正常,除了最后一个/hello我得到这个错误:

{
    "stringValue": "\"hello\"",
    "valueType": "string",
    "kind": "ObjectId",
    "value": "hello",
    "path": "_id",
    "reason": {},
    "name": "CastError",
    "message": "Cast to ObjectId failed for value \"hello\" (type string) at path \"_id\" for model \"product\""
}

这是我的index.js

import mongoose from "mongoose";
import  express, { json }  from "express";
import 'dotenv/config'
import productRouter from './routes/productR.js' 

const app = express()

const connectionToDB = async () => {
  try {
    await mongoose.connect('mongodb://127.0.0.1:27017/testingDB')
    console.log('Connected to mongoDB');
  } catch (error) {
    console.log(error);
  }
}

app.use(json())
app.use('/products', productRouter)

app.listen(process.env.PORT, ()=>{
    connectionToDB()
    console.log('Server in up at '+ process.env.PORT);
})

这是我的产品模型

import mongoose from "mongoose";

const productSchema = new mongoose.Schema({
    name:{
        type:String
    },
    brand:{
        type: String,
    },
    size:{
        type:[String],
    },
    desc:{
        type:String
    },
    price:{
        type:Number
    }, 
    category:{
        type:String
    },
    picture:{
        type:String
    }
})

export default mongoose.model('product',productSchema)

我的产品路由器

import express  from "express";
import { addProduct, deleteProduct, getProduct, getProducts, updateProduct } from "../controllers/productC.js";

const router = express.Router()

router.post('/',addProduct)
router.put('/:id',updateProduct)
router.delete('/:id',deleteProduct)
router.get('/:id',getProduct)
router.get('/',getProducts)

router.get("/hello",(req, res)=>{
    res.json('5464')
})

export default router;

我的产品控制器

import Product from '../models/productM.js'

export const addProduct = async (req, res)=>{
    const newProduct = Product(req.body)
    try {
        const savedProduct = await newProduct.save()
        res.status(200).json(savedProduct)
    } catch (error) {
        res.status(500).json(error)
    }
}

export const updateProduct = async (req, res) => {
    try {
        const updatedProduct = await Product.findById(req.params.id)
        if(req.body.name) { updatedProduct.name = req.body.name}
        if(req.body.brand) { updatedProduct.brand = req.body.brand}
        if(req.body.size) { updatedProduct.size =(req.body.size)}
        if(req.body.desc) { updatedProduct.desc = req.body.desc}
        if(req.body.price) { updatedProduct.price = req.body.price}
        if(req.body.picture) { updatedProduct.picture = req.body.picture}
        if(req.body.category) { updatedProduct.category = req.body.category}
        await updatedProduct.save()
        res.status(200).json(updatedProduct)
    } catch (error) {
        res.status(500).json(error)
    }
}

export const deleteProduct = async (req, res) => {
    
    try {
        await Product.findByIdAndDelete(req.params.id)
        res.status(200).json(`The product (${req.params.id}) has been deleted`)
    } catch (error) {
        res.status(500).json(error)
    }
}

export const getProduct = async (req, res) => {
    const productID = req.params.id
    try {
        const foundProduct = await Product.findById(productID)
        res.status(200).json(foundProduct)
    } catch (error) {
        res.status(500).json(error)
    }
}

export const getProducts = async (req, res) => {
    const {min,max, ...others} = req.query
    const name = req.query.name || "";
    const category = req.query.category || "";
    const brand = req.query.brand || "";
    console.log(name);
    try {
        // const foundProducts = await Product.find({
        //     price:{$gt:parseInt(min) || 1, $lt:parseInt(max) || 999}
        // })
        const foundProducts = await Product.find({$and:[
            { price:{$gte:parseInt(min) || 1, $lte:parseInt(max) || 9999}},
            {name: {$regex: `${name}` || "" , $options: 'i' }},
            {brand: {$regex: `${brand}` || "" , $options: 'i' }},
            {category: {$regex: `${category}` || "" , $options: 'i' }}
        ]})
        res.status(200).json(foundProducts)
    } catch (error) {
        res.status(500).json(error)
    }
}

// export const getCats = async () => {
//     try {
//         res.status(200).json('here')
//     } catch (error) {
//         res.status(500).json(error)
//     }
// }

我改变了方法来发布它的工作,但当我返回到get方法时,即使我删除了路由,我也会遇到同样的问题,错误仍然存在:(

t2a7ltrp

t2a7ltrp1#

在您的产品路由器中,您有以下路由:router.get('/:id', getProduct)
此路由期望在URL中传递id参数,但当您访问/hello时,它将hello视为id参数,这会导致错误,因为hello无法转换为ObjectId
你应该使用一个linting工具,比如eslint。你应该阅读以下文章:How do I ask a good question?

相关问题