Search code examples
javascriptnode.jsmongodbexpressmongoose

get specfic objects from array inside array of object express js mongodb


i have array of friends inside users array , i need to get all friends of specific user by email that approved field is true

in nodejs i have user mongo schema

const UserSchema = mongoose.Schema({
     username : {type: String , required :true},
     email : {type: String , required :true, unique: true, match: /.+\@.+\..+/},
     password : {type: String , required :true},
     friends : {type:[{username : String, approved: Boolean}]},
});

[
  {
    "username": "ali",
    "email": "ali200@gmail,com",
    "password": "pdcjjfefmkadjakefkeofjafjafsfjsalnnryifajs",
    "friends": [
      {
        "id": "1",
        "username": "gamal",
        "approved": true
      },
      {
        "id": "2",
        "username": "osama",
        "approved": false
      },
      {
        "id": "3",
        "username": "john",
        "approved": true
      }
    ]
  }
]

i need to get array of friends object that approved field is true like this

[
     {
        "id": "1",
        "username": "gamal",
        "approved": true
      },
      {
        "id": "3",
        "username": "john",
        "approved": true
      }

]

Code from comment:

router.get("/getFriends", (req, res) => {
      var email = getEmailFromToken(req.header("Authorization"));
      User.findOne({
        email: email
      }).then((user) => res.status(200).send({
        friends: user.friends
      }));

Solution

  • by using code, it can be done with

    User.findOne({ email: email }).then((user) => {
      const friends = user.friends.filter((f) => f.approved);
      res.status(200).send({ friends });
    });
    

    or you can use query instead

    User.agregate([
      {
        $match: {
          email: "[email protected]",
        },
      },
      {
        $project: {
          _id: 1,
          friends: {
            $filter: {
              input: "$friends",
              as: "truelyFriend",
              cond: {
                $eq: ["$$truelyFriend.approved"],
              },
            },
          },
        },
      },
    ]).then((user) => {
      res.status(200).send({ friends: user[0].friends });
    });
    

    mongo tester : mongo-playground