A.S.Abir
A.S.Abir

Reputation: 99

express js fetch data using mongoose

I am trying to find data using id from MongoDB (mongoose). I have checked req.parms.id for "string" and length "24". If length does't match then show check message. But some id provide me data, show show no data, some time show me server error.

This is code for check parms id

    export const donarDetailsMiddleware: RequestHandler = (req, res, next) => {
      const donarId = typeof req.params.donar === 'string' && req.params.donar.length === 24 ? req.params.donar : false;

      if (donarId) next();
      else res.status(400).json({ message: 'invalid donar id' });
   };
export const showDonarDetailsHandler: RequestHandler = async (req, res, next) => {

  try {
    const getDonarDetails = await DonarModel.find({ _id: req.params.donar });

    if (getDonarDetails && getDonarDetails.length === 1) {
      res.status(200).json({ message: 'donar fetch success', donar: getDonarDetails[0] });
    }
    else {
      res.status(200).json({
        error: "no donar found",
      });
    }
  }
  catch (err) {
    res.status(500).json({
      error: "There are server error !!!!",
      err
    });
  }
};

Providing "63124b286a250a870ec4b43k" id, this show this error

{
    "error": "There are server error !!!!",
    "err": {
        "stringValue": "\"63124b286a250a870ec4b43k\"",
        "valueType": "string",
        "kind": "ObjectId",
        "value": "63124b286a250a870ec4b43k",
        "path": "_id",
        "reason": {},
        "name": "CastError",
        "message": "Cast to ObjectId failed for value \"63124b286a250a870ec4b43k\" (type string) at path \"_id\" for model \"Donar\""
    }
}

for this "63124b286a250a870ec4b43a" it show expected message for no data

and for this id "63124b286a250a870ec4b43c" it show my data correctly.

where is the problem?

Upvotes: 1

Views: 48

Answers (1)

Matt
Matt

Reputation: 74670

MongoDB ObjectID's are 12 byte values, represented by a 24 character hexadecimal string

^[a-f0-9]{24}$

A string containing a k is invalid and can't be cast to the Mongoose ObjectID type.

Upvotes: 2

Related Questions