mongoose query: find an object by id in an array

后端 未结 2 591
粉色の甜心
粉色の甜心 2021-02-10 13:18

How could I find an image by id in this Schema. I have the id of the User and the id of the image I am looking for. What would be the best way to do this and do all images in th

相关标签:
2条回答
  • 2021-02-10 13:28
    userSchema .find({facebook.id: "some ID",{ "images.id": { $in: [ id1, id2, ...idn] }}
    

    since images are inside the document you can have same ID's however every time you query you should keep in mind that you send some other parameters such as facebook.id or facebook.email along with image id's to retrieve them. Otherwise you end up getting all that might be irrelevant only because you decide to keep same ID's for images.

    0 讨论(0)
  • 2021-02-10 13:29

    When you are interested in the full object it is a simple find:

    .find({"facebook.id":"<id>", "images.id":<image-id>})
    

    I don't think that there is a way to reduce the image array in the result.

    To update a single element in the image array you can use this:

    .update({"facebook.id":"<id>", "images.id":<image-id>}, {$set : {"images.$.main" :false} } );
    
    0 讨论(0)
提交回复
热议问题