使用 Mongoose 查询嵌套的嵌入文档

Posted

技术标签:

【中文标题】使用 Mongoose 查询嵌套的嵌入文档【英文标题】:Querying nested embedded documents with Mongoose 【发布时间】:2012-06-23 15:12:07 【问题描述】:

我正在尝试在嵌套的嵌入式文档中进行查询。我试图“填充”结果,但失败了。

如何在 find 调用中取回所有图书详细信息?我想要用户书架上的所有书籍对象,我可以从中获取数据?

###

Trying to query nested embedded documents using Mongoose.

Database Outline for example

An Owner has multiple bookshelves which each have an array of books.
A book is not unique, and the same book could be on many different shelves.

###

mongoose = require("mongoose")
Schema = mongoose.Schema
mongoose.connect "localhost", "d1"

bookSchema = new Schema(title: String)
Book = mongoose.model("Book", bookSchema)

shelfBookSchema = new Schema(
  book:
    type: Schema.ObjectId
    ref: "Book"
  )

shelfSchema = new Schema(
  name: String
  books: [ shelfBookSchema ]
  )

Shelf = mongoose.model("Shelf", shelfSchema)

ownerSchema = new Schema(
  firstName: String
  shelves: [ shelfSchema ]
  )

Owner = mongoose.model("Owner", ownerSchema)

mongoose.connection.on "open", ->
  book1 = new Book(title:"How to make stuff")
  book1.save (err) ->
    throw err if err

    owner = new Owner(firstName:"John")
    shelf = new Shelf(name:"DIY Shelf")
    shelf.books.push
      _id: book1._id
      book: book1._id
    owner.shelves.push shelf
    owner.save (err) ->
      throw err if err

      #Let's find one owner and get all of his bookshelves and the books they containa
      Owner.findOne().populate("shelves.books.book").exec (err, owner) ->
        console.error owner.shelves[0].books

        ### Log shows:

         book: 4fe3047401fc23e79c000003,
        _id: 4fe3047401fc23e79c000003 ]

        Great but how do I get the values of book like the title etc??

        ###

        mongoose.connection.db.dropDatabase ->
          mongoose.connection.close()

【问题讨论】:

最好将接受检查移至现在解决问题的“深度人口”答案。 【参考方案1】:

在 Mongoose 3.6 中添加了深层人口。 https://github.com/LearnBoost/mongoose/issues/1377#issuecomment-15911192

对于你的例子,它会是这样的:

Owner.find().populate('shelves').exec(PopulateBooks);

function PopulateBooks(err, owners) 
      if(err) throw err;
      // Deep population is here
      Book.populate(owners,  path: 'shelves.books' ).exec(callback);

【讨论】:

这似乎在 v3.6 和 v4.0.8 之间发生了变化。填充返回一个承诺,您可以将其传递给一个函数:mongoosejs.com/docs/api.html#model_Model.populate【参考方案2】:

目前不支持嵌套子文档填充。我为这篇文章添加了一个指向开放 github 问题的链接,以供将来跟踪。

https://github.com/LearnBoost/mongoose/issues/601

【讨论】:

以上是关于使用 Mongoose 查询嵌套的嵌入文档的主要内容,如果未能解决你的问题,请参考以下文章

Expressjs Mongoose 发现嵌套的嵌入文档未定义

如何填充嵌套的 Mongoose 嵌入文档

使用 mongoose 查询嵌套文档

如何通过 Mongoose 查询对嵌入文档数组进行排序?

Mongoose - 使用 find() 查询文档,其中嵌套数组值的总和在一定范围内

Mongoose 查询返回带有空数组的嵌套文档