2015-02-17 49 views
1

我不知道如何甚至說這個問題......但這裏是一個嘗試。我將這本書稱爲「父母」模型,並將作者稱爲「孩子」模型。如何查詢子模型在Mongoose中基於父模型限制結果

我有兩個貓鼬模型---作者和書籍:

var Author = mongoose.model("Author", { 
    name: String 
}); 

var Book = mongoose.model("Book", { 
    title: String, 
    inPrint: Boolean, 
    authors: [ { type: mongoose.Schema.ObjectId, ref: "Author"} ] 
}); 

我想運行一個查詢這將返回所有誰擁有圖書(父模型)的作者(子模型)的這在打印。

我可以想辦法與多個查詢做到這一點,但我想知道是否有辦法用一個查詢來做到這一點。

回答

1

您可以使用populate作爲docs

說有MongoDB中沒有加入,但有時我們還是想在其他集合文件的引用。這是人口進入的地方。在這裏閱讀更多關於如何在其他查詢結果中包含來自其他集合的文檔。

在你的情況下,它看起來東西這樣的:

Book.find().populate('authors') 
.where('inPrint').equals(true) 
.select('authors') 
.exec(function(books) { 
    // Now you should have an array of books containing authors, which can be 
    // mapped to a single array. 
}); 
1

我只是在這個問題絆倒今天解決了這個問題:

Author.find() 
    .populate({ path: 'books', match: { inPrint: true } }) 
    .exec(function (err, results) { 
     console.log(results); // Should do the trick 
    }); 

中出現的魔法populatematch選項,它指向要填充的嵌套文檔的屬性。

而且check my original post

編輯:我混淆了書的作者,現在是糾正

+0

我不認爲這會工作,因爲是從Author--書沒有路徑,你可以得到從作者書 - 但不是相反。 – 2015-02-18 13:52:24