使用Mongoose查询嵌套嵌套文档 [英] Querying nested embedded documents with Mongoose

查看:708
本文介绍了使用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()


推荐答案

在蒙古人3.6中增加了深度种群。 https://github.com/LearnBoost/mongoose/issues/1377#issuecomment-15911192

Deep population was added in Mongoose 3.6. 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);
}

这篇关于使用Mongoose查询嵌套嵌套文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆