I have two Schemas in MongoDB one is Author and second is Book. Author has many books.
Author Schema:
var authorSchema = {
name:{
type: String
},
books:[{
type: Schema.Types.ObjectId,
ref: 'Book'
}]
}
Book Schema:
var bookSchema = {
title:{
type: String
}
}
Now I am creating a book listing page in which I want to fetch all the authors of each book using the book collection. How can I do that?
If you are actually asking that you want the "relation" to be done the "other way around" then the anwser is to "store" that relation in that way in the first place.
Therefore:
var bookSchema = new Schema({
title: { type: String },
author: { type: Schema.Types.ObjectId }
});
So look at the "relation" as being "two way" in the sense that each object has the required information to "relate" to the other.
Which basically means you can then do:
Books.find({ "author": authorId })
.populate("author")
.exec(function(err,books) {
// stuff in here
});
Without the horrible construct that is:
Books.find().execute(function(err,books) {
var results = [];
async.each(books,function(book,callback) {
Author.findOne({ "books": book._id },function(err,author) {
var obj = book.toObject();
book.author = author;
results.push(books);
callback(err);
});
},
function(err) {
if (err) throw err;
console.dir(results);
});
})
So do it better as suggested originally.