skip to Main Content

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

2

Answers


  1. Your logic is correct but little syntax issue. Try this

    const check = await User.find({userName: userName, friends: { $in: [friend] }});
    
    Login or Signup to reply.
  2. 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
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search