[SOLVED] getMovieByID not working with default param

The implementation works with this:

$match: {
_id: ObjectId(id),
}

But not with this:

$match: {
_id: id,
}

Is this intended or am I doing something wrong?

Yes it is intended.

What you are missing is that parameters to the function ( usually coming from the route parameters ) are actually a “string” and not an ObjectId. Therefore the function of ObjectId() is used to cast this value into the correct type.

Users of the mongoose library often find this confusing as the implemented methods there actually allow you to simply pass in these “strings” without the explicit casting of types. The actual reason for this relates to mongoose schema which actually defines a type for the _id field in the schema and does the type conversion for you.

The real case though is just like how the implementation in the mongoose code that is hidden from you, that you actually do need to convert these types.

You can also demonstrate this in the mongo shell by simply attempting to match a document by the _id value ( provided it is the default ObjectId type of course ) as a “string”, as opposed to a proper ObjectId instance. Moreover the same applies for ALL BSON types, as 1 is different to "1" and true is different to "true" etc.


NOTE: This is not the ONLY place where you will be expected to cast a “string” value into an ObjectId. So other answers here actually depend on you understanding this.

1 Like

I know how these work. :sweat_smile: Just curious about the comment saying that the $match stage is done but in reality it requires revise. :yum:

But thanks though! Got the answer I was looking for!

What do you mean “requires revise”?

The code with $match: { _id: ObjectId(_id) } IS exactly how it is shipped. If you think it was otherwise then I suggest you download the application source again.

There has been some earlier commentary that possibly some people downloading on the very first day of this run of the course got a stale release of the code and data, but it has been extensively noted on several other threads here that you should be downloading all of that “afresh” if you experience such problems.

Moreover, this is all actually addressed on other threads.

Might have missed the other threads. I am done with this and next week’s works so I don’t think I need to download it again. Thanks a ton for the help though. :slight_smile: