0

I have a user document like this

{
    "_id": "userid",
    "posts": [
        {
            "_id": {
                "$oid": "5ad68c4febe84802fcd9feb0"
            },
            "likes": [
                {
                    "_id": {
                        "$oid": "5ad626d578c7b21c0806042e"
                    }
                }
            ]
        }
    ]
}

I want to get the document by post id and find out if a user id is already inside the likes array of the same post

How can i do this in mongoose ?

Thanks in advance.

Asaf Aviv
  • 11,279
  • 1
  • 28
  • 45
  • Is what you posted a plain Javascript object, or something relating to mongoose? – CertainPerformance Apr 18 '18 at 03:56
  • Thats my mongodb document – Asaf Aviv Apr 18 '18 at 04:10
  • Posts is static or dinamik.This mean posts[0],posts[1].... or only posts. – ŞükSefHam Apr 18 '18 at 05:14
  • Posts is an array of multiple documents ive managed to do it like this but it dosent seem a good way to do it User.find( { "posts._id": req.params.id, }, "posts.$", (err, doc) => { if (doc[0].posts[0].likes.some(like => like._id == req.user.id)) { console.log('this user already likes this post') } } ) – Asaf Aviv Apr 18 '18 at 05:17
  • @NeilLunn i dont have a problem to retrieve the document im just looking for a way to know if it exists in the likes array from the query, i dont want to loop over it on the server – Asaf Aviv Apr 18 '18 at 05:24
  • *"I want to get the document by post id and find out if a user id is already inside the likes array of the same post"* - This is the question which is already comprehensively answered. That's what you asked, and you've been pointed at the solution. Another variant was on the link that closed your previous question as well. Read and learn. It's what you want. – Neil Lunn Apr 18 '18 at 06:35

0 Answers0