0

I'm trying to search an object array for a specific value inside of a query. How would I get the user "taylor" from the following lines of an already made query?

I've tried $elemMatch :{user:"taylor"} but that just returns all accounts following Taylor. I need it to just get the username starman's following of Taylor. Context: I'm making an if statement to search if someone is already following an account so I can res.json a message saying "You already follow them!" to stop duplicate followers.

{
    "success": true,
    "user": {
        "name": "Kyle",
        "username": "starman",
        "bio": "Why yes I am a groupie, how did you know?",
        "avatar": "https://i.imgur.com/YfyWjq4.gif",
        "phone": "6788456456",
        "followers": [],
        "following": [
            {
                "user": "taylor"
            },
            {
                "user": "trevor"
            }
        ]
    }
}
Alwaysblue
  • 9,948
  • 38
  • 121
  • 210
  • I did it myself, never mind. I just did it outside the model in my usercheck with vanilla javascript and filter. – Corey Trowbridge Oct 29 '19 at 23:08
  • I was already typing out an answer. Anyways, MongoDB handles array very nicely, if you were to write a query in this case, you can just treat the `following` array likes it's an actual object so you can do this to check if this user already has a follower named `taylor` : `db..find({ "user.following.user" : "taylor" })` – Tunmee Oct 29 '19 at 23:10

1 Answers1

0

Try this Query

db.testers.aggregate([
{ $match: {"user.following.user":"taylor"} } ,
{ "$addFields": {
        "user.following": 
          {
              "$filter": {
                      "input": "$user.following",
                      "as": "sn",
                      "cond": {
                        "$and": [
                          { "$eq": [ "$$sn.user", "taylor" ] },
                     ]
              }
          }
       } 

    }},
])   
Mahesh Bhatnagar
  • 1,042
  • 1
  • 7
  • 8