簡體   English   中英

在 mongodb 中的嵌套文檔中查詢

[英]Query in nested document in mongodb

這是我的貓鼬模式:

const chapterSchema = mongoose.Schema({
title: {
    type: String
},
number: {
    type: Number
}
})

const bookSchema = mongoose.Schema({
    title: {
        type: String
    },
    author: {
        type: String
    },
    chapters: [chapterSchema]
})

const Book = mongoose.model('Book', bookSchema)
module.exports = Book

這是我的數據庫:

{
"_id": "5f56f8e66a7eee227c1acc0a",
"title": "Book1",
"author": "Author1",
"chapters": [{
    "_id": "5f56fa47a78fbf03cc32d16d",
    "title": "Chapter1",
    "number": 1
}, {
    "_id": "5f56fad10820300de031317f",
    "title": "Chapter2",
    "number": 2,
}]
}

我想通過它的 id 從章節數組中找到一個特定的章節 所以,我寫了這段代碼:

router.get('/:id', async function (req, res) {
try {
    const id = req.params.id
    await Book.findById(id, function (err, chapter) {
        res.render('chapter.hbs', {
            chapter: chapter
        })
    })
} catch (error) {
    res.redirect('/')
}
})

根據章節id,我想要這個結果:

{
    "_id": "5f56fa47a78fbf03cc32d16d",
    "title": "Chapter1",
    "number": 1
}

或者

{
    "_id": "5f56fad10820300de031317f",
    "title": "Chapter2",
    "number": 2,
}

我應該怎么做才能使用它的 id 查找特定章節?

您正在使用章節 Id 的 findById 搜索 Book,它不會給出結果,因為它不是 Book Id,

您需要為此使用$elemMatch

檢查此查詢 Mongoose 子數組中的對象以供參考

您可以使用聚合函數執行此操作。

router.get('/:id', async function (req, res) {
  try {
    const id = req.params.id
    await Books.aggregate([
      {
        $project: {
          title: 1,
          author: 1,
          chapters: {
            $filter: {
              input: "$chapters",
              as: "chapter",
              cond: {
                $eq: [
                  "$$chapter.id", id
                ]
              }
            }
          }
        }
      }
    ])
  } catch (error) {
    res.redirect('/')
  }
})

您可以使用aggregate()函數,

  • $match你的條件
  • $filter獲取特定章節 ID
  • $replaceWith替換 root 中的章節
const id = mongoose.Types.ObjectId(req.params.id);

let chapter = await Book.aggregate([
  { $match: { "chapters._id": id } },
  {
    $replaceWith: {
      $arrayElemAt: [
        {
          $filter: {
            input: "$chapters",
            cond: { $eq: ["$$this._id", id] }
          }
        },
        0
      ]
    }
  }
]);

console.log(chapter);

操場

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM