Search code examples
node.jsmongodbmongoosesession-cookies

MongoDB Cast to ObjectId failed for value "" at path "" for model ""


I have a simple code using session, that checks If there is a user_id propriety in the session then, take it and using mongoose databse find that user. This is the code:

let user_id = req.session.user_id;
    if(user_id)
    {
        const user = await User.findById({ user_id });
        req.user = user;
        req.userobjs = await Utilities.GetAllObjs(req.user);
    }

A user looks like this:

{
  projects: {
    journals: [
      new ObjectId("61841e95088d9c1a65a8ddc9"),
      new ObjectId("61841ee6088d9c1a65a8de13")
    ],
    lists: []
  },
  _id: new ObjectId("61841e86088d9c1a65a8ddc4"),
  username: 'dd',
  password: '$2b$12$CfEYYSDycuxO9Slv1C8Fu.WHOeiBgTiJfToOSUozMGNyWduZY5pLW',
  __v: 6
}

And , as you may think the user_id string from session, used in the code looks like this:

61841e86088d9c1a65a8ddc4

But the problem is that when executing the code with a valid user_id in session, I get this error:

UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "{ user_id: '61841e86088d9c1a65a8ddc4' }" (type Object) at path "_id" for model "User"


Solution

  • The problem was here:

    if(user_id)
    {
        let user = await User.findById({user_id});
        req.user = user;
    

    The function Model.findById requires only a string argument, and I passed {} around it.

    This is what it should look like:

        let user = await User.findById(user_id); //without {}