Agent K
Agent K

Reputation: 351

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.

Upvotes: 1

Views: 1830

Answers (2)

Cuong Le Ngoc
Cuong Le Ngoc

Reputation: 11975

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)...

Upvotes: 4

im2rnado
im2rnado

Reputation: 91

Maybe this would work

const allTheRelatedData = (publiserId, bookId) => {
    return new Promise((resolve, reject) => {
        try {
            myBookSchema
                .find()
                .then((data) => {
                    const item = data.filter(i => i.publisherId === publisherId && i.books.includes(book => book.bookId === bookId))
                    if (item) {
                        console.log(item);
                        resolve(item);
                    } else {
                        console.log("Not found");
                        reject("Not found");
                })
                .catch((error) => {
                    console.log(error);
                    reject(error);
                });
        } catch (error) {
            console.log(error);
            reject(error);
        }
    });
};

Upvotes: 1

Related Questions