Cast to ObjectId failed for value \ "private \" at path \ "_id \" for model \ "Product \"

0

Hi, I'm doing an API Rest with Nodejs and MongoDB and I have the following problem:

{
"message": "Error al realizar la petición: CastError: Cast to ObjectId failed for value \"private\" at path \"_id\" for model \"Product\""}

I do not understand what that means to me, to contextualize I add some parts of the code that I have:

'use strict'

const Product = require('../models/product')

function getProduct (req, res) {
    let productId = req.params.productId

    Product.findById(productId, (err, product) => {
        if (err) return res.status(500).send({message: 'Error al realizar la petición: ${err}'})
        if (!product) return res.status(404).send({message: 'El producto no existe'})

        res.status(200).send({ product })
    })
}

function getProducts (req, res) {
    Product.find({}, (err, products) => {
        if (err) return res.status(500).send({message: 'Error al realizar la petición: ${err}'})
    if (!products) return res.status(404).send({message: 'No existen        productos'})

        res.send(200, { products })             
    })
}
'use strict'

const express = require('express')
const productCtrl = require('../controllers/product')
const auth = require('../middlewares/auth')
const api = express.Router()


api.get('/product', productCtrl.getProducts)
api.get('/product/:productId', productCtrl.getProduct)
api.post('/product', productCtrl.saveProduct)
api.put('/product/:productId', productCtrl.updateProduct)
api.delete('/product/:productId', productCtrl.deleteProduct)
api.get('/private', auth, (req, res) => {
    res.status(200).send({ message: 'Tienes acceso' })
})

module.exports = api
'use strict'

const mongoose = require('mongoose')
const Schema = mongoose.Schema

const ProductSchema = Schema({
    name: String,
    picture: String,
    price: {type: Number, default: 0 },
    category: { type: String, enum: ['computers', 'phones', 'accesories']},
    description: String
})

module.exports = mongoose.model('Product', ProductSchema)

An error is caused when I do a GET for path http://localhost:3001/api/product/private/

I am new to this and I feel stuck at this point, I appreciate any contribution. Greetings.

    
asked by Aljadis Tavera 18.08.2018 в 11:44
source

1 answer

1

MongoDB uses an id type for documents called ObjectId. An ObjectId has its own format, an example of ObjectId: "507f1f77bcf86cd799439011".

Following your model, when you insert products, for each one a different id is generated with the ObjectId format.

When you call link , what happens inside is that you go to findById telling you that the id is " private ", and when you try to convert it to ObjectId it fails because it is not a valid ObjectId. And it is the error that is returning you "CastError: Cast to ObjectId failed for value \" private \ ""

    
answered by 19.08.2018 в 10:55