查询与猫鼬嵌套嵌入文档(Querying nested embedded documents wit

2019-06-25 16:16发布

我想这是嵌套嵌入文档中进行查询。 我已经尝试“填入”的结果,但失败了。

我该如何找回所有的里面找到称这本书的细节? 我希望所有对用户架子,我可以从获取数据的书的对象?

###

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

Answer 1:

深人口在猫鼬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);
}


Answer 2:

现在的问题是,不支持嵌套子文件人口。 我添加了一个链接到这个职位的开放github上的问题为未来的跟踪。

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



文章来源: Querying nested embedded documents with Mongoose