0

I have a model in mongodb that looks something like this...

{
    username: 'bob', 
    user_id: '12345',
    post: 'Hey everyone, this is my post',
    photoID: RANDOM_GENERATED_NUMBER, // each user has their own photoID
    comments: [
        {
            username: 'tom', 
            user_id: '54321',
            post: 'Hey everyone, this is comment 1',
            photoID: RANDOM_GENERATED_NUMBER, // each user has their own photoID
            responses: [
                {
                    username: 'bob', 
                    user_id: '12345',
                    post: 'Hey everyone, this is response 2',
                    photoID: RANDOM_GENERATED_NUMBER, // each user has their own photoID
                },
                {
                    username: 'will', 
                    user_id: '35791',
                    post: 'Hey everyone, this is response 2',
                    photoID: RANDOM_GENERATED_NUMBER, // each user has their own photoID
                }
            ]
        },
        {
            username: 'bob', 
            user_id: '12345',
            post: 'Hey everyone, this is comment 2',
            photoID: RANDOM_GENERATED_NUMBER, // each user has their own photoID
            responses: []
        }
    ]
}

On my site, everytime a user changes their profile picture, they get a new 'photoID', referencing the picture, so it can easily be displayed with their username above any posts they make. Because of this, when a user updates their profile picture and gets a new 'photoID', I need to be able to make a query to this 'Post' model that searches for any 'posts', 'comments' or 'responses' that were posted by 'bob'. I then need to update the photoID for that 'post', 'comment' or 'response'.

Is there a query I can use to do this?

willmahon
  • 319
  • 4
  • 13

1 Answers1

1

You can use a nested elemMatch query.

Possible duplicate of How to use elemMatch to match nested array

Victor Wilson
  • 1,720
  • 1
  • 11
  • 22
  • I'm aware of how to edit nested arrays, just wanted to know if it's possible to search different layers and then edit different layers in one query? I don't think it is though, so I guess I'll have to make 3 separate queries for each layer in the document. – willmahon Jun 19 '21 at 17:14