I don't really understand findOne(), or find() too for that matter

so, i did that Use model.findOne() to Return a Single Matching Document from Your Database challenge

const findOneByFood = (food, done) => { 
  Person.findOne({favoriteFoods: food}, (err, data)=> err ? done(err) : done(null, data));
};

it worked but i am still confused. favoriteFoods key in the model signifies an array of strings and neither the very sketchy challenge, nor even the mongoose docs say if the search succeeds only when the whole array is identical to the query or it can search by one food from the array too. i mean suppose i have a document “person” who has favorite foods [“tuna”, “ice cream”], will the search succeed if i look for both of those foods in an array like {favoriteFoods: [“tuna”, “ice cream”]} or i can look by say “tuna” only like {favoriteFoods: “tuna”} or {favoriteFoods: [“tuna”]}?

When running a query like Person.findOne({favoriteFoods: food}, where favoriteFoods is an array, mongodb will simply check that the food is present in the array. It’s smart enough to know this without us having to to tell it anything else.
{favoriteFoods: “tuna”} and {favoriteFoods: [“tuna”]} would actually return different results. Wrapping the search term in an array will now only return documents where favorteFoods is exactly ["tuna"]. But if you just pass it in as a string it will check to see that the array contains the search term and it doesn’t have to be an exact match

2 Likes