0

I've got a friend route which I registered on the user route. I've registered the user route in the app,

I've used mongoose.Types.ObjectId in the user schema

Mongoose Version: 5.9.19

In User.js

router.use("/friend", FriendRouter);

then in FriendRoute(i.e. friend.js)

router.get("/suggestions", checkAuth, async (req, res) => {
  console.log(req.userId);

  try {
    let user = await User.findById(req.userId);
    let suggestions = "";
    if (user.friends.length !== 0) {
      suggestions = await User.find({
        $and: [
          { _id: { $nin: user.friends } },
          { _id: { $nin: user.friendRequests } },
          { _id: { $nin: user.sentRequests } },
        ],
      })
        .select("name")
        .limit(20);
    } else {
      suggestions = await User.find({
        $and: [
          { _id: { $ne: user._id } },
          { _id: { $nin: user.friendRequests } },
          { _id: { $nin: user.sentRequests } },
        ],
      })
        .select("name")
        .limit(20);
    }
    res.status(200).json({ suggestions: suggestions });
  } catch (err) {
    console.log(err);

    res.status(500).json({ error: err });
  }
});

This works when I write it as the first function. If I move it to the last, it throws CastError. Here's the log. I even tried deleting the route, it still throws the same error.

CastError: Cast to ObjectId failed for value "suggestions" at path "_id" for model "User"
    at model.Query.exec (/home/plaster-saint/Instagram-Clone/backend/node_modules/mongoose/lib/query.js:4351:21)
    at model.Query.Query.then (/home/plaster-saint/Instagram-Clone/backend/node_modules/mongoose/lib/query.js:4443:15)
    at processTicksAndRejections (internal/process/task_queues.js:97:5) {
  messageFormat: undefined,
  stringValue: '"suggestions"',
  kind: 'ObjectId',
  value: 'suggestions',
  path: '_id',
  reason: Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters
      at new ObjectID (/home/plaster-saint/Instagram-Clone/backend/node_modules/bson/lib/bson/objectid.js:59:11)
      at castObjectId (/home/plaster-saint/Instagram-Clone/backend/node_modules/mongoose/lib/cast/objectid.js:25:12)
      at ObjectId.cast (/home/plaster-saint/Instagram-Clone/backend/node_modules/mongoose/lib/schema/objectid.js:267:12)
      at ObjectId.SchemaType.applySetters (/home/plaster-saint/Instagram-Clone/backend/node_modules/mongoose/lib/schematype.js:1031:12)
      at ObjectId.SchemaType._castForQuery (/home/plaster-saint/Instagram-Clone/backend/node_modules/mongoose/lib/schematype.js:1459:15)
      at ObjectId.SchemaType.castForQuery (/home/plaster-saint/Instagram-Clone/backend/node_modules/mongoose/lib/schematype.js:1449:15)
      at ObjectId.SchemaType.castForQueryWrapper (/home/plaster-saint/Instagram-Clone/backend/node_modules/mongoose/lib/schematype.js:1428:15)
      at cast (/home/plaster-saint/Instagram-Clone/backend/node_modules/mongoose/lib/cast.js:326:32)
      at model.Query.Query.cast (/home/plaster-saint/Instagram-Clone/backend/node_modules/mongoose/lib/query.js:4740:12)
      at model.Query.Query._castConditions (/home/plaster-saint/Instagram-Clone/backend/node_modules/mongoose/lib/query.js:1865:10)
      at model.Query.<anonymous> (/home/plaster-saint/Instagram-Clone/backend/node_modules/mongoose/lib/query.js:2122:8)
      at model.Query._wrappedThunk [as _findOne] (/home/plaster-saint/Instagram-Clone/backend/node_modules/mongoose/lib/helpers/query/wrapThunk.js:16:8)
      at /home/plaster-saint/Instagram-Clone/backend/node_modules/kareem/index.js:369:33
      at processTicksAndRejections (internal/process/task_queues.js:79:11)
}
GET /user/friend/suggestions 500 8.473 ms - 108

I've checked some other answers regarding the CastError.

https://stackoverflow.com/a/54552580/10866130

I saw this one and tried it and it works. but why?

Update

This was a simple routing issue. I had a route like router.get('/:id.(req.res))

The suggestion get request was hitting that route instead of

router.get('/sugesstions.(req.res))

because it was matching router.get('/:id.(req.res)) first.

Hamada
  • 1,836
  • 3
  • 13
  • 27
anotherChowdhury
  • 103
  • 3
  • 10

1 Answers1

0

This was a simple routing issue. I had a route like router.get('/:id.(req.res))

The suggestion get request was hitting that route instead of

router.get('/sugesstions.(req.res))

because it was matching router.get('/:id.(req.res)) first.

anotherChowdhury
  • 103
  • 3
  • 10