Question about the mongoose findOne method and its filtering argument

Tell us what’s happening:
I’m working on this exercise where we need to complete a function using findOne mongoose method.

For context, the schema for our model is:

  name : {
    type: String,
    required: true
age :  Number,
favoriteFoods : {
  type: Array,
  default: []

In the exercice, we must write a function, with a foodparameter, and that returns the first item in DB that has this foodargument as part of the favoriteFoods array.

I searched and struggled. Eventually checked out the solution below

  Person.findOne({favoriteFoods: food}, function (err, data) {
    if (err) return console.log(err);
    done(null, data);

And now I don’t get how this can work since favoriteFoods is an array and food isn’t. Is that under the hood dark mongoose magic or am I missing something?

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.55 Safari/537.36

Challenge: Use model.findOne() to Return a Single Matching Document from Your Database

Link to the challenge:

Some of this will be speculation.

MongoDB is fine with a query like that so its not mongoose

When you make a query with a given key in this case favoriteFoods it will check for that key and if the value matches, and it so happens that you can query for an array by only specifying a single value of the array as a sort of short hand.

The reason this may be a thing is because if you want to hand in array instead of a single value then the whole array needs to match which would become very tedious.

An important thing to note due to this is that give a collection such as:

{favoriteFoods: ['food1', 'food2', 'food3']},
{favoriteFoods: 'food1'}

Bot of those items would match the query {favoriteFoods: 'food1'}

1 Like

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