I have two collections: authors and books
author example:
{
_id: "605f6746c114544ee04228bd"
firstName: "firstName",
lastName: "lastName",
}
book example:
{
_id: "605f6746c114544ee04228bd"
title: "title",
pages: 350,
}
I want to get the list of books with thier author firstName and lastName.
here is my current code:
let books;
books = await Book.find();
books.forEach(async (book, i) => {
const author = await Author.findOne(
{ _id: book.authorId },
{ firstName: 1, lastName: 1, _id: 0 }
);
books[i].authorFirstName = author.firstName;
books[i].authorLastName = author.lastName;
});
This is not a good practice because for each book I execut another request to mongodb database! Any better solution?
Mongoose version to join two models with relationship
books = await Book.find({}).populate({ path:"authorId", select:{firstName:1, lastName:1}})
Using aggregation
let books = await Book.aggregation([
{
$lookup:{
from:"collection_of_author",
localField: "authorId",
foreignField: "_id",
as: "author"
}
},
{
$unwind: {
path:"authorId",
preserveNullAndEmptyArrays:true
}
}])
Clean code and higher performance using mongoose populate
import Book from "../models/Book";
import Author from "../models/Author";
let books = await Book.find().populate({
path: "authorId",
model: Author,
select: { firstName: 1, lastName: 1, _id: 0 },
});