我在MERN堆栈的Electron 商务平台上工作.在我的项目中,我有三个架构:User、Product和Cart.购物车架构同时引用用户架构和产品架构.
以下是我的简化架构 struct :
CartModel.js
const mongoose = require("mongoose");
const { Schema, model } = mongoose;
const cartSchema = new Schema(
{
user: { type: Schema.Types.ObjectId, ref: "User", required: true },
product: { type: Schema.Types.ObjectId, ref: "Product", required: true },
unit: { type: Number, required: true },
},
{ timestamps: true, versionKey: false }
);
const cartModel = model("Cart", cartSchema);
module.exports = cartModel;
ProductModel.js
const mongoose = require("mongoose");
const { Schema, model } = mongoose;
const productSchema = new Schema(
{
title: String,
short_des: String,
price: Number,
discount_price: Number,
image: String,
stock: String,
star: String,
},
{ timestamps: true, versionKey: false }
);
const productModel = model("Product", productSchema);
module.exports = productModel;
UserModel.js
const mongoose = require("mongoose");
const { Schema, model } = mongoose;
const userSchema = new Schema(
{
name: { type: String, required: true },
email: { type: String, unique: true, required: true },
password: { type: String, required: true },
},
{ timestamps: true, versionKey: false }
);
const userModel = model("User", userSchema);
module.exports = userModel;
我的问题是,在我的购物车控制器,我试图定义一个查询加入购物车,用户和产品模型,并试图提取特定的信息,但my query isn't working as expected.
我需要提取按用户分组的每个产品的以下信息:
- 购物车对象ID和单位
- 用户名和邮箱
- 产品名称和价格
我try 在数组中返回结果,这样我就可以在我的react前端中使用map方法来显示数据.
CartController.js
exports.cartList = async (req, res) => {
try {
let userId = new mongoose.Types.ObjectId(req.user._id);
let result = await cartModel.aggregate([
{ $match: { user: userId } },
{
$lookup: {
from: "users", // Name of the User model collection
localField: "user",
foreignField: "_id",
as: "userDetails",
},
},
{
$lookup: {
from: "products", // Name of the Product model collection
localField: "product",
foreignField: "_id",
as: "productDetails",
},
},
{
$group: {
_id: "$user",
},
},
]);
res.status(200).json({ status: true, data: result });
} catch (error) {
res.status(200).json({ status: false, data: error.message });
}
};
购物车模型数据示例如下
{
"_id": {
"$oid": "6592be024fc8de3f1771a9e1"
},
"product": {
"$oid": "657fab1586f102e3657bf034"
},
"user": {
"$oid": "6559696bfa9b7df357161a81"
},
"createdAt": {
"$date": "2024-01-01T13:28:34.452Z"
},
"unit": 4,
"updatedAt": {
"$date": "2024-01-01T13:28:46.865Z"
}
},
{
"_id": {
"$oid": "6592dc014fc8de3f1771bc3f"
},
"product": {
"$oid": "65801d5e2c366e8773ada21f"
},
"user": {
"$oid": "6559696bfa9b7df357161a81"
},
"createdAt": {
"$date": "2024-01-01T15:36:33.420Z"
},
"unit": 3,
"updatedAt": {
"$date": "2024-01-01T15:36:37.161Z"
}
}
谁可以提供一个聚合查询的指导或示例,该聚合查询以适合在Reaction中映射的格式从多个集合(购物车、用户和产品)中检索指定的信息?如有任何帮助或建议,我们将不胜感激.谢谢!