如何在 Mongoose 中查询基于父模型限制结果的子模型
How Do I Query A Child Model Restricting Results Based on Parent Model in Mongoose
我什至不确定如何表述这个问题...但请尝试一下。我将本书称为 "Parent" 模型,将作者称为 "Child" 模型。
我有两个猫鼬模型---作者和书籍:
var Author = mongoose.model("Author", {
name: String
});
var Book = mongoose.model("Book", {
title: String,
inPrint: Boolean,
authors: [ { type: mongoose.Schema.ObjectId, ref: "Author"} ]
});
我正在尝试 运行 一个查询,该查询将 return 所有拥有印刷书籍(父模型)的作者(子模型)。
我可以想办法用多个查询来完成,但我想知道是否有办法用一个查询来完成。
您可以按照 docs
中所述使用 populate
There are no joins in MongoDB but sometimes we still want references to documents in other collections. This is where population comes in. Read more about how to include documents from other collections in your query results here.
在你的情况下,它看起来 像这样:
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.
});
我今天偶然发现了这个问题并解决了它:
Author.find()
.populate({ path: 'books', match: { inPrint: true } })
.exec(function (err, results) {
console.log(results); // Should do the trick
});
魔术发生在 populate
的 match
选项中,它引用要填充的嵌套文档的 属性。
还有check my original post
编辑:我曾让作者混淆书籍,现在已更正
我什至不确定如何表述这个问题...但请尝试一下。我将本书称为 "Parent" 模型,将作者称为 "Child" 模型。
我有两个猫鼬模型---作者和书籍:
var Author = mongoose.model("Author", {
name: String
});
var Book = mongoose.model("Book", {
title: String,
inPrint: Boolean,
authors: [ { type: mongoose.Schema.ObjectId, ref: "Author"} ]
});
我正在尝试 运行 一个查询,该查询将 return 所有拥有印刷书籍(父模型)的作者(子模型)。
我可以想办法用多个查询来完成,但我想知道是否有办法用一个查询来完成。
您可以按照 docs
中所述使用populate
There are no joins in MongoDB but sometimes we still want references to documents in other collections. This is where population comes in. Read more about how to include documents from other collections in your query results here.
在你的情况下,它看起来 像这样:
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.
});
我今天偶然发现了这个问题并解决了它:
Author.find()
.populate({ path: 'books', match: { inPrint: true } })
.exec(function (err, results) {
console.log(results); // Should do the trick
});
魔术发生在 populate
的 match
选项中,它引用要填充的嵌套文档的 属性。
还有check my original post
编辑:我曾让作者混淆书籍,现在已更正