Home > Software design >  How to pass a text in a query instead of objectId in mongoose?
How to pass a text in a query instead of objectId in mongoose?

Time:06-01

I want to pass an plain text value instead of ObjectId in a query string like this: 127.0.0.1:3000/trips?from=mumbai&to=ahmedabad&date=2022-06-02

Instead of 127.0.0.1:3000/trips?from=6295f0986f9e32990d8b3488&to=6295f0c06f9e32990d8b348b&date=2022-06-02.

I am getting the result whenever I pass the object ID as a value but when I pass the plain text value I am getting this error: Cast to ObjectId failed for value "mumbai" (type string) at path "Location.to" for model "Route"

I have referenced Location table into the route table like this:

const routeSchema = new mongoose.Schema(
  {
    Location: {
      from: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Location",
        required: true,
      },
      to: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Location",
        required: true,
      },
    },
    busId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Bus",
      required: true,
    },
    date: {
      type: String,
      required: true,
    },
  },
  {
    timestamps: true,
  }
);

Here is the Location table:

const locationSchema = new mongoose.Schema(
  {
    location: {
      name: {
        type: String,
        unique: true,
        required: true,
        lowercase: true,
      },
      subLocation: [String],
    },
  },
  {
    timestamps: true,
  }
);

Here is the GET request to trip data.

router.get("/trips", async (req, res) => {
  if (!req.query.from || !req.query.to || !req.query.date) {
    return res.send({
      error: "Please enter the data to get the trip",
    });
  }
  const { from, to, date } = req.query;

  const routes = await Route.find({
    "Location.from": from,
    "Location.to": to,
    date,
  }).populate({
      path: "Location.from Location.to",
      select: "-location.subLocation -_id -createdAt -updatedAt -__v",
    }).select(["-_id", "-busId", "-createdAt", "-updatedAt", "-__v"]);

  return !routes ? res.status(500).send() : res.status(200).send(routes);
});

I want to pass a plain text as query value instead of objectID and still want to get the result.

Is there any way to do that?

CodePudding user response:

If you want to execute the query as text then remove mongoose.Schema.Types.ObjectId as type from Route model and set type as String. If any of the keys have type mongoose.Schema.Types.ObjectId then MongoDB only accepts an alphanumeric string of 24 characters. Otherwise, it throws a casting error.

CodePudding user response:

You are receiving string from the request. You need to convert it to ObjectID before querying the database.

Reference

db.collection.find({
  "$expr": {
    "$eq": [
      "$Location.from",
      {
        "$toObjectId": "6295f0986f9e32990d8b3488"
      }
    ]
  }
})

Similarly, you append Location.to in the same query

awaitRoute.find({
  "$expr": {
    "$and": [
      {
        "$eq": [
          "$Location.from",
          {
            "$toObjectId": from
          }
        ]
      },
      {
        $eq: [
          "$Location.to",
          {
            "$toObjectId": to
          }
        ]
      }
    ]
  }





 
  • Related