如何从 Mongoose 中的嵌套数组中查找数据?

How to find data from nested array in Mongoose?

我有两个 ID:publisherID 和 BookID。

我的猫鼬数据库看起来像:

现在的问题是:我想找到 userId,其中 publishderId 是 59l55llopd3W1FuosGgN,bookId 是 G1Vfe2NwS3sy -qhT1J0g6

我创建了以下函数,其中 returns 空数据。

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);
        }
    });
};

当我运行这段代码时,它给出了空数据。请帮助,我尝试了很多解决方案,例如位置、匹配等。没有任何效果。请帮忙

也许这行得通

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);
        }
    });
};

您可以使用 $ projection operator 来做到这一点:

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

然后用data.books[0].userId可以得到userId,记得用if (data && data.books && data.books.length)...

检查数据或书籍是否存在