amyst
amyst

Reputation: 616

Unrecognized expression '$toObjectId' in mongoose aggregation

In my mongoose aggregation, I am getting error as Unrecognized expression '$toObjectId'. My MongoDB version is 4.2.5 and the mongoose version is 5.9.6. As per documentation, this operator is available in 4.x version and ideally should have worked.

  const trips = await Tickets.aggregate([
              {$match: {trip: Utils.strToObjectId(tripid) }},
              {$project: {_id:0,status:1, bookedBy:1,name:1,totalFare:1, seats:1, mode:1 }},
              {$group: {_id: {$toObjectId:"$bookedBy"}, bookings: {$push: {status: "$status", mode:"$mode", name: "$name", from: "$sourceCity", to: "$destinationCity", seats: "$seats" ,fare: "$totalFare", pnr: "$shortid" }}  }},
              {$lookup: {from:"users", localField:"bookedBy", foreignField:"_id",as:"user"}},
              ]);

In my case bookedBy get converted to string which is not matching in $lookup pipeline. so to resolve this I am trying to convert it to objectId.

Any help suggestion is appreciated.

Upvotes: 0

Views: 3376

Answers (2)

Bartłomiej Mogielski
Bartłomiej Mogielski

Reputation: 11

I had this problem and was wrestling with it for two days,
The solution for me was making sure my MongoDB is up to date,

I was hosting mine on MLab.com which provided me with Mongo 3.6, whilst $toObjectId is available only from Mongo 4.0

I migrated my server to Mongo Atlas for free which provided me with the up to date version and everything ran smoothly.

Upvotes: 1

naveen
naveen

Reputation: 25

If you are having trouble with accessing objectId created by MongoDB,then why don't you create your own unique object Id and access wherever you want. By using this you don't need to worry about converting to object ID. For Example,

const MUUID = require('uuid-mongodb'); 
id: {
        type: 'object',
        unique: true,
        default: () => MUUID.v1().toString(),
    }

I am just a beginner. I am sorry if my answer is inconvenient or irrelevant. It's just an idea.Thank you

Upvotes: 0

Related Questions