2012-06-21 322 views
4

我想在嵌套嵌入式文檔內查詢。我試圖「填充」結果,但是失敗了。用Mongoose查詢嵌套嵌入式文檔

如何找回查找呼叫中的所有書籍詳情?我想要一個用戶書架上的所有書籍對象,我可以從中獲取數據?

### 

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

這將是很好的接受支票移動到「深人口」的答案,現在解決了這個問題。 – JohnnyHK

回答

8

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

非常好的soluation !!!!! – Steven

+0

這似乎已在v3.6和v4.0.8之間發生變化。填充返回一個承諾,你可以傳遞一個函數:http://mongoosejs.com/docs/api.html#model_Model.populate –