Home > front end >  How can I find if a value is equal to something in a mongodb model having an array?
How can I find if a value is equal to something in a mongodb model having an array?

Time:10-06

I am trying to check if my user has a specific value in his friends column.

The code i am trying is

exports.findFriend = async (userName, user) => {
    return await User.findOne({ _id: user._id }, { friends:{ userName: userName } } });
};

This is not working properly.

CodePudding user response:

You should use the keyword $elemMatch, because you are trying to find a value inside an array

Use the following code

exports.findFriend = async (userName, user) => {
    return await User.findOne({ _id: user._id }, { friends: { $elemMatch: { userName: userName } } });
};
  • Related