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
Your logic is correct but little syntax issue. Try this
You don’t need
$in
. Mongo will check whole array if you just do this: