简体   繁体   English

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

[英]Querying nested embedded documents with Mongoose

I'm trying to query inside an embedded document that is nested. 我正在尝试查询嵌套的嵌入式文档。 I've attempted to 'populate' the results but that fails. 我试图“填充”结果,但失败了。

How do I get back all of the book details inside the find call? 如何在查找呼叫中找回所有书籍详细信息? I want all of the book objects on a users shelf that I can get data from? 我想要用户架子上的所有书籍对象,我可以从中获取数据吗?

###

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

Deep population was added in Mongoose 3.6. Mongoose 3.6增加了深度人口。 https://github.com/LearnBoost/mongoose/issues/1377#issuecomment-15911192 https://github.com/LearnBoost/mongoose/issues/1377#issuecomment-15911192

For your example, it would be something like: 对于您的示例,它将是这样的:

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

right now nested sub document population is not supported. 现在不支持嵌套的子文档填充。 i added a link to this post to the open github issue for future tracking. 我在这个帖子中添加了一个链接到open github问题,以便将来跟踪。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM