Search code examples
arraysmongodbmongoosemongoose-schemamern

How to find data from nested array in Mongoose?


I have two ids: publisherID and BookID.

My mongoose database looks like:enter image description here

Now the question is: I want to find userId where the publishderId is 59l55llopd3W1FuosGgN and the bookId is G1Vfe2NwS3sy-qhT1J0g6

I've created the following function which returns the null data.

const allTheRelatedData = (publiserId, bookId) => {
    return new Promise((resolve, reject) => {
        try {
            myBookSchema
                .findOne({
                    publisherId: publisherId,
                    "books.$.bookId": bookId,
                })
                .then((data) => {
                    console.log(data);
                    resolve(data);
                })
                .catch((error) => {
                    console.log(error);
                    reject(error);
                });
        } catch (error) {
            console.log(error);
            reject(error);
        }
    });
};

When I run this code, it gives null data. Please help, I tried many solutions such as positional, match, etc. Nothing is working. Please help.


Solution

  • You can use $ projection operator to do that:

    myBookSchema
      .findOne({
        publisherId: publisherId,
        "books.bookId": bookId,
      }, {
        "books.$": 1
      }
    ).then((data) => {...
    

    Then you can get userId with data.books[0].userId and remember to check if data or book exists with if (data && data.books && data.books.length)...