Вы можете получить всю связанную информацию с заполнением без необходимости карты.
exports.getAllBlogs = async (req, res) => {
try {
const blogs = await Blog.find({})
.sort({ created_at: -1 })
.populate("author", "-password")
.populate({
path: "comments",
populate: {
path: "user",
select: "-password"
}
});
return res.status(200).json(blogs);
} catch (error) {
console.log(error);
res.status(500).json({ error: "Something went wrong" });
}
};
Это даст примерный результат, подобный этому:
[
{
"_id": "5e53b2896f41c765fc4defa1",
"title": "Blog2 Title",
"body": "Blog2 Body",
"author": {
"_id": "5e53b1726f41c765fc4def9c",
"email": "user1@gmail.com",
"name": "User1",
"created_at": "2020-02-24T11:20:18.343Z",
"updated_at": "2020-02-24T11:20:18.343Z",
"id": "5e53b1726f41c765fc4def9c"
},
"created_at": "2020-02-24T11:24:57.078Z",
"updated_at": "2020-02-24T11:24:57.078Z",
"__v": 0,
"comments": [
{
"_id": "5e53b34c6f41c765fc4defa5",
"body": "Comment3 (user2 on user1's blog2)",
"user": {
"_id": "5e53b1906f41c765fc4def9d",
"email": "user2@gmail.com",
"name": "User2",
"created_at": "2020-02-24T11:20:48.070Z",
"updated_at": "2020-02-24T11:20:48.070Z",
"__v": 0,
"id": "5e53b1906f41c765fc4def9d"
},
"blog": "5e53b2896f41c765fc4defa1",
"created_at": "2020-02-24T11:28:12.551Z",
"updated_at": "2020-02-24T11:28:12.551Z"
}
],
"id": "5e53b2896f41c765fc4defa1"
},
{
"_id": "5e53b26c6f41c765fc4def9f",
"title": "Blog1 Title",
"body": "Blog1 Body",
"author": {
"_id": "5e53b1726f41c765fc4def9c",
"email": "user1@gmail.com",
"name": "User1",
"created_at": "2020-02-24T11:20:18.343Z",
"updated_at": "2020-02-24T11:20:18.343Z",
"id": "5e53b1726f41c765fc4def9c"
},
"created_at": "2020-02-24T11:24:28.895Z",
"updated_at": "2020-02-24T11:24:28.895Z",
"__v": 0,
"comments": [
{
"_id": "5e53b2f86f41c765fc4defa3",
"body": "Comment1 (user2 on user1's blog1)",
"user": {
"_id": "5e53b1906f41c765fc4def9d",
"email": "user2@gmail.com",
"name": "User2",
"created_at": "2020-02-24T11:20:48.070Z",
"updated_at": "2020-02-24T11:20:48.070Z",
"id": "5e53b1906f41c765fc4def9d"
},
"blog": "5e53b26c6f41c765fc4def9f",
"created_at": "2020-02-24T11:26:48.506Z",
"updated_at": "2020-02-24T11:26:48.506Z"
},
{
"_id": "5e53b3246f41c765fc4defa4",
"body": "Comment2 (user3 on user1's blog1)",
"user": {
"_id": "5e53b1996f41c765fc4def9e",
"email": "user3@gmail.com",
"name": "User3",
"created_at": "2020-02-24T11:20:57.488Z",
"updated_at": "2020-02-24T11:20:57.488Z",
"id": "5e53b1996f41c765fc4def9e"
},
"blog": "5e53b26c6f41c765fc4def9f",
"created_at": "2020-02-24T11:27:32.305Z",
"updated_at": "2020-02-24T11:27:32.305Z"
}
],
"id": "5e53b26c6f41c765fc4def9f"
}
]