Home > Enterprise >  Check if value exists inside nested array in mongoDB
Check if value exists inside nested array in mongoDB

Time:09-22

Im trying to check if a value I sent as a request already exists in an array inside of a specific User. The format of the data is as so

{
    "_id": "63233972df0f14076e027106",
    "firstName": "mako",
    "lastName": "mako",
    "userName": "mako",
    "email": "[email protected]",
    "friends": [
        "Josh"
    ],
    "__v": 0
}

Im sending the following request

{
    "userName": "mako",
    "friend": "Josh"
}

And I want to check if "friend" in request already exists in the data set and return a true or false.

I've tried using $exists and $in but I cant get to get the syntax right

const checkFriend = async(req, res, next)=>{
  try {
    const {userName, friend} = req.body
    const check = await User.findOne({userName: userName, $in: {friends: friend}})
    res.send(check)
  } catch (error) {
    
  }
}

My NodeJS code for my attempt, the only one that returned anything

CodePudding user response:

Your logic is correct but little syntax issue. Try this

const check = await User.find({userName: userName, friends: { $in: [friend] }});

CodePudding user response:

You don't need $in. Mongo will check whole array if you just do this:

const isFound = await User.findOne({ userName: userName, friends: friend }).lean();

if (isFound) {
  // Do something
} else {
  // Do something else
}
  • Related