To fix Mongoose: CastError: Cast to ObjectId failed for value "[object Object]" at path "_id" with Node.js, we make sure we’re casting a valid value to an object ID.
For instance, we write
const mongoose = require("mongoose");
console.log(mongoose.Types.ObjectId.isValid("53cb6b9b4f4ddef1ad47f943"));
console.log(mongoose.Types.ObjectId.isValid("whatever"));
to use the mongoose.Types.ObjectId.isValid
to check if the value we’re trying to cast to an object ID is a valid value.
The first console log should log true
since it’s a valid object ID value.
And the 2nd one logs false
since it’s not a valid object ID value.