Javascript: requires a projection keyword otherwise projection is ignored

While working on the mflix tutorial I have run into an issue defining a projection on db.model.find command.

In mongo shell I can run a command:

movies.find({countries: { $in: {countries}}, {title: 1})

and get either one country or multiple countries returned with {_id, title}.

In the moviesDAO.js {getMoviesByCountry} if the find command is formatted as above it fails the projections test. When I log the results to the movies variable it has the entire record not just {_id, title}.

If I modify the find command to be:

movies.find({countries: { $in: {countries}}, {projection: {title: 1}})

then the result is once again just {_id, title} as expected.

I cannot find in the MongoDB documentation any reference to using “projection” as a keyword to define a projection on a find.

And why does the result differ between mongo shell and javascript implementation?

Hello welcome : )

node.js driver and mongo-shell are different.
They have similar syntax but not excactly the same.

When you use the driver see the driver api
https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#find
Here you can see the projection as option.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.