it happens when you pass an invalid id to mongoose. so first check it before proceeding, using mongoose isValid function import mongoose from "mongoose"; // add this inside your route if( !
Types. ObjectId . A SchemaType is just a configuration object for Mongoose. An instance of the mongoose. ObjectId SchemaType doesn't actually create MongoDB ObjectIds, it is just a configuration for a path in a schema.
Mongoose's findById
method casts the id
parameter to the type of the model's _id
field so that it can properly query for the matching doc. This is an ObjectId but "foo"
is not a valid ObjectId so the cast fails.
This doesn't happen with 41224d776a326fb40f000001
because that string is a valid ObjectId.
One way to resolve this is to add a check prior to your findById
call to see if id
is a valid ObjectId or not like so:
if (id.match(/^[0-9a-fA-F]{24}$/)) {
// Yes, it's a valid ObjectId, proceed with `findById` call.
}
Use existing functions for checking ObjectID.
var mongoose = require('mongoose');
mongoose.Types.ObjectId.isValid('your id here');
I had to move my routes on top of other routes that are catching the route parameters:
// require express and express router
const express = require("express");
const router = express.Router();
// move this `/post/like` route on top
router.put("/post/like", requireSignin, like);
// keep the route with route parameter `/:postId` below regular routes
router.get("/post/:postId", singlePost);
I have the same issue I add
_id: String .in schema then it start work
Are you parsing that string as ObjectId
?
Here in my application, what I do is:
ObjectId.fromString( myObjectIdString );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With