【发布时间】:2021-10-22 02:58:11
【问题描述】:
我正在努力编写 每个类别的 4 个产品。我所做的是
exports.recentproducts = catchAsync(async (req, res, next) => {
const doc = await Product.aggregate([
{ $sort: { date: -1 } },
{
$replaceRoot: {
newRoot: {
$mergeObjects: [{ $arrayElemAt: ['$products', 0] }, '$$ROOT'],
},
},
},
{
$group: {
_id: '$productCategory',
products: { $push: '$$ROOT' },
},
},
{
$project: {
// pagination for products
products: {
$slice: ['$products', 4],
},
_id: 1,
},
},
{
$lookup: {
from: 'Shop',
localField: 'shopId',
foreignField: '_id',
as: 'shop',
},
},
]);
文档模型
const mongoose = require('mongoose');
var ProductSchema = mongoose.Schema({
title: {
type: String,
require: [true, 'Product must have a Title!'],
},
productCategory: {
type: String,
require: [true, 'Product must have a Category!'],
},
shopId: {
type: mongoose.Schema.ObjectId,
ref: 'Shop',
require: [true, 'Product must have a Shop!'],
},
});
var Product = mongoose.model('Product', ProductSchema);
module.exports = Product;
预期结果---
result= [
{
productCategory: "Graphics",
products:[//4 products object here
{
must populate shop data
}
]
},
{
productCategory: "3d",
products:[//4 products object here]
},
//there are seven categories I have like that
]
我所做的代码运行良好,但有两个问题 即使我尝试了查找,它也不会从 Shop 模型中填充 shopId 它不按降序对产品进行排序(不按日期排序)
【问题讨论】:
-
您需要向我们展示文件和预期结果
-
我已经添加了更多细节,请您查看
标签: javascript node.js mongodb mongoose mongodb-query