Home > front end >  How to return a Boolean if a value exists in a subdocument which is an array using mongoose
How to return a Boolean if a value exists in a subdocument which is an array using mongoose

Time:06-13

If my user schema looks like following

const user = new schema(
  Id: {
    type: ObjectId,
  },
  followers: {
    type: Array,
    default: [],
  },
)
 

And I want to iterate the followers array and return a boolean true or false based on a search Id that exists inside the array.

for example: If I have a document userid : 123, and user with userid as 234 is following the user with the Id 123. So the document for 123 looks something like this :

{
  Id: 123,
  followers:[234,356,....]
}
 

What query should be constructed such that there is an iteration of the followers array and if the value(req.body.userId) in the request parameter (req.params.id) exist then the query returns a true else it returns a false

const User = require("../models/users");
router.put("/followuser/:id", async (req, res) => {
  if (req.params.id !==req.body.userId){   
    const followed = await User.exists(/*code to check if 234(req.body.userId) is present in the followers array*/) 
    if(followed == true) {
        // further code to allow following the user

    }else {

    res.status(400).json("You Already follow the user")
  }

  }else {

    res.status(400).json("Cannot follow yourself mate")
  }

}  )

CodePudding user response:

There are lots of ways to do this, and hopefully this query can be adapted for your purposes.

db.users.find(
{ "Id": 123 },  // <-- this user's ID
{
  "_id": 0,
  "present": { "$in": [ 234, "$followers" ] }
})  //                   ^
    //          Is this ID already a follower?

Try it on mongoplayground.net.

  • Related