How do I handle a mongodb id between angular and mongoose?

Discussão em 'Angular' iniciado por koque, Dezembro 18, 2024.

  1. koque

    koque Guest

    Because of Typescript's strong typing, I am passing Mongodb's _id as a string in angular. Example:

    public setSelectedProduct = async (productId: string) => {...}


    When I pass productId to the backend and try to access Mongodb using Mongoose in Node.js, it tells me productId is not a valid Mongodb id.

    exports.getProduct = async (req, res) => {
    console.log('req.params.productId', req.params.productId)
    const productId = req.params.productId;

    // const productId = new mongoose.Types.ObjectId(Number(req.params.productId));


    try {
    const product = await Product.findOne({_id: productId})
    console.log('product', product);
    // res.status(200).json(product);
    } catch(error) {
    console.error(error);
    res.status(500).send("Problem getting selected product.");
    }
    }


    CastError: Cast to ObjectId failed for value " 67420003204128e379f42946" (type string) at path "_id" for model "Product"
    ​

    I try to convert from string to ObjectId using the following:

    const productId = new mongoose.Types.ObjectId(Number(req.params.productId));


    But the existing associated product is not returned.

    How do I handle this?

    Continue reading...

Compartilhe esta Página