Let's assume I have mongoose models for books and pages like this:
mongoose.model("Book", new Schema({
title: String
});
and this
mongoose.model("Page", new Schema({
pageNumber: Number,
_bookId: {type: ObjectId, ref: "Book"}
});
Every page keeps track which book it belongs to. Now I want to have an array of books that have a page with pageNumber 500.
I could do the following:
Page.find({pageNumber: 500})
.populate("_bookId")
.then(function (pages) {
var books = [];
pages.forEach(function (page) {
books.push(page._bookId); // page._bookId now contains a Book document
});
return q(books);
}).then(function (books) {
// Do something with the books
});
Yet, the part where I loop over the pages seems cumbersome and that kind of extraction could probably be done by mongo. My question is how that would work.
Is using populate even the best way to go here? I would like to keep the schemas the way they are though.