#mongodb #mongoose #mongodb-query #aggregate #pipeline
Вопрос:
Как бы я ни старался, коллекция книг продолжает выводить повторяющиеся значения для одной коллекции в базе данных в зависимости от количества ее подкатегорий. Если общая длина подкатегорий равна трем для конкретной книги, книги выводят три массива для одной коллекции. Ниже длина подкатегорий равна трем, и в книгах выводится три дубликата одного значения. Я бы хотел, чтобы коллекция книг отображала только одно значение, как оно есть в базе данных, а не дубликаты одного значения из базы данных
Пожалуйста, помогите мне в этом
Вывод Кодов
books: Array(3)
0: {_id: '6158beb4c6ac564594e409e1', user: {…}, title: 'Amazon announces Astro the home robot', content: '<p>The company said it can be remote-controlled wh… hundreds of thousands of players.</p><p><br></p>', description: 'Amazon is launching Astro, its first household robot, powered by its Alexa smart home technology', …}
1: {_id: '6158beb4c6ac564594e409e1', user: {…}, title: 'Amazon announces Astro the home robot', content: '<p>The company said it can be remote-controlled wh… hundreds of thousands of players.</p><p><br></p>', description: 'Amazon is launching Astro, its first household robot, powered by its Alexa smart home technology', …}
2: {_id: '6158beb4c6ac564594e409e1', user: {…}, title: 'Amazon announces Astro the home robot', content: '<p>The company said it can be remote-controlled wh… hundreds of thousands of players.</p><p><br></p>', description: 'Amazon is launching Astro, its first household robot, powered by its Alexa smart home technology', …}
count: 3
name: "technology"
subCategories: Array(3)
0: {_id: '615782c9ef37913ce4b240e1', subCategories: Array(0), user: {…}, name: 'Django', category_root: '615746f2963a3032bc6812e0', …}
1: {_id: '61577ebcef37913ce4b240ba', subCategories: Array(0), user: {…}, name: 'Java', category_root: '615746f2963a3032bc6812e0', …}
2: {_id: '6157550cef37913ce4b24085', subCategorifes: Array(0), user: {…}, name: 'Python', category_root: '615746f2963a3032bc6812e0', …}
Модель
user: { type: mongoose.Types.ObjectId, ref: 'user' },
title: {
type: String,
require: true,
trim: true,
minLength: 10,
maxLength: 50
},
content: {
type: String,
require: true,
minLength: 2000
},
description: {
type: String,
require: true,
trim: true,
minLength: 50,
maxLength: 200
},
thumbnail: {
type: String,
require: true
},
category: { type: mongoose.Types.ObjectId, ref: 'category' },
subCategories: { type: mongoose.Types.ObjectId, ref: 'category' }
Ниже приведен используемый агрегатный метод
await books.aggregate([
//User
{
$match: {
subCategories: { $exists: false },
category: { $exists: true },
category_root: { $exists: false },
sub_user: { $exists: false }
}
},
{
$lookup:{
from: "users",
let: { user_id: "$user" },
pipeline: [
{ $match: { $expr: { $eq: ["$_id", "$user_id"] } } },
{ $project: { password: 0 } }
],
as: "user"
}
},
// array -> object
{ $unwind: { path: "$user", preserveNullAndEmptyArrays: true } },
// Category
{
$lookup: {
from: "categories",
"localField": "category",
"foreignField": "_id",
"as": "category"
}
},
// array -> object
{ $unwind: { path: "$category", preserveNullAndEmptyArrays: true } },
// SubCategories Category
{
$lookup: {
from: "categories",
"let": { sub_id: "$category.subCategories" },
"pipeline": [
{ $match: { $expr: { $in: ["$_id", {$ifNull:["$sub_id",[]]}] } } },
{
$lookup: {
"from" : "users",
"let": { user_id: "$user" },
"pipeline": [
{ $match: { $expr: { $eq: ["$_id", "$user_id"] } } },
{ $project: { name: 1, avatar: 1 } }
],
"as": "user"
}
},
{ $unwind: "$user" },
{
$lookup: {
"from" : "users",
"let": { user_id: "$sub_user" },
"pipeline": [
{ $match: { $expr: { $eq: ["$_id", "$user_id"] } } },
{ $project: { name: 1, avatar: 1 } }
],
"as": "sub_user"
}
},
{ $unwind: "$sub_user" }
],
"as": "subCategories"
}
},
{ $unwind: { path: "$subCategories", preserveNullAndEmptyArrays: true }},
// Sorting
{ $sort: { "createdAt": -1 } },
//Group by category
{
$group: {
_id: "$category._id",
name: { $first: "$category.name" },
books: { $push: "$ROOT" },
subCategories: { $addToSet: "$subCategories" },
count: { $sum: 1 }
}
},
//Pagination for books
{
$project: {
books: {
$slice: ['$books', 0, 4]
},
subCategories: 1,
count: 1,
name: 1
}
}
])