Я хочу агрегировать по коллекции, в которой указан тип. Типы поступают из строки запроса и могут быть днем, месяцем или годом. В зависимости от того, какой тип выбирают пользователи, я хочу сгруппировать. Например: если пользователь выбирает «месяц», я хочу сгруппировать по месяцам.
Event.aggregate([
{
$lookup: { from: Product.collection.name, localField: 'product', foreignField: '_id', as: 'product' }
},
{
$group: {
_id: { $month: { date: "$date" } },
price: { $sum: "$price" },
result: { $mergeObjects: { name: "$product.name", _id: "$product._id" } },
count: { $sum: 1 }
},
},
]).then(response => {
console.log(response)
res.send(response)
})
Я не могу понять, как найти чистое решение. До сих пор единственный способ, который я нашел, заключался в использовании условного выражения перед Model.aggregate ([]) ...
if (req.query.dateAvailability && req.query.dateAvailability === 'month') {
Event.aggregate([
{
$lookup: { from: Product.collection.name, localField: 'product', foreignField: '_id', as: 'product' }
},
{
$group: {
_id: { $month: { date: "$date" } },
price: { $sum: "$price" },
result: { $mergeObjects: { name: "$product.name", _id: "$product._id" } },
count: { $sum: 1 }
},
},
]).then(response => {
console.log(response)
res.send(response)
})
} else if (req.query.dateAvailability && req.query.dateAvailability === 'day') {
Event.aggregate([
{
$lookup: { from: Product.collection.name, localField: 'product', foreignField: '_id', as: 'product' }
},
{
$group: {
_id: { $dateToString: { format: "%d-%m-%Y", date: "$date" } },
price: { $sum: "$price" },
result: { $mergeObjects: { name: "$product.name", _id: "$product._id" } },
count: { $sum: 1 }
},
},
]).then(response => {
console.log(response)
res.send(response)
})
} else if (req.query.dateAvailability && req.query.dateAvailability === 'year') {
Event.aggregate([
{
$lookup: { from: Product.collection.name, localField: 'product', foreignField: '_id', as: 'product' }
},
{
$group: {
_id: { $year: { date: "$date" } },
price: { $sum: "$price" },
result: { $mergeObjects: { name: "$product.name", _id: "$product._id" } },
count: { $sum: 1 }
},
},
]).then(response => {
console.log(response)
res.send(response)
})
}
Событие модели:
const EventSchema = new Schema({
client: {
type: [{
type: Schema.Types.ObjectId,
ref: 'Client'
}]
},
product: {
type: [{
type: Schema.Types.ObjectId,
ref: 'Product'
}]
},
date: {
type: Date,
maxlength: 64,
lowercase: true,
trim: true
},
place: {
type: String,
maxlength: 1200,
minlength: 1,
},
price: {
type: Number
},
comment: {
type: String,
maxlength: 12000,
minlength: 1,
},
status: {
type: Number,
min: 0,
max: 1,
default: 0,
validate: {
validator: Number.isInteger,
message: '{VALUE} is not an integer value'
}
},
},
{
toObject: { virtuals: true },
toJSON: { virtuals: true }
},
{
timestamps: true
},
);