Search code examples
databasemongodbexpressmongooseejs

CastError: Cast to ObjectId failed for value "1" (type string) at path "_id" for model "Stocks"


I am trying to edit the whole form by using the updateOne function of mongoose but whenever I clicks the edit button, it shows error CastError: Cast to ObjectId failed for value "1" (type string) at path "_id" for model "Stocks".

counter.js

const counterSchema = {
    id: {
        type: String
    },
    
    seq: {
        type: Number
    }
}

stocks.js

const stockSchema = new Schema({
    id: {
        type: Number
    },
    flowerName: {
        type: String,
        required: true
    }
    },{timestamps: true }
);

This is from my post Method wherein I add a value to the form

Counter.findOneAndUpdate(
        {id: "autoval"}, 
        {"$inc":{"seq": 1}}, 
        {new: true}, (err, cd) => {


            let seqID;
            if(cd==null) {
                const newValue = new Counter({id: "autoval", seq:1})
                newValue.save() 
                seqID = 1
            } else { 
                seqID = cd.seq
            }

            const qty = Number(req.body.quantity)
            const price = Number(req.body.pricePieces)
           
            const stock = new Stocks ({
                id: seqID,
                flowerName: req.body.flowerName
            })
            stock.save()
                .then(result => {
                    res.redirect('flowers-in-stock');
                }).catch(err => console.log(err));
        }
    )

And I want to proceed in the edit page

   Stocks.findById(req.params.id)
        .then (stock => {
            res.render('flowers-in-stock-edit', {stocks: stock})
        }).catch(err => console.log(err));
}

Solution

  • The findById function matches its parameter with the _id field in the document in MongoDB.

    Your schema defines id but not _id, so the _id will be automatically created on insert, and will be type ObjectId.

    findById attempts to cast its parameter to match the datatype of the _id field. The error message indicates that you are passing "1" as the value to find, which findById is attempting to cast to ObjectId. "1" is not a valid ObjectId, so that fails.

    To search based on your id field, use findOne instead of findById:

    Stocks.findOne({id: req.params.id})