基于Mongoose查询指定客户订单及订单内商品的技术咨询
Mongoose 查询需求解决方案
模型代码
Customers 模型
const {Schema, model, Types} = require("mongoose"); const customerSchema = new Schema({ Fullname: { type: String, trim: true }, username: { type: String, unique: true, required: true, trim: true }, email: { type: String, unique: true, required: true, match: [/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/, "Please enter a valid email address",] }, PhoneNo: { type: String, //unique: true, //required: true, }, CreatedAt: { type: Date, }, LastVisitDate: { type: Date, }, orders: [ { type: Schema.Types.ObjectId, ref: "Order" }, ], { toJSON: { virtuals: true, getters: true }, id: false }); const Customer = model("Customer", customerSchema);
Order 模型
const {Schema, model, Types} = require("mongoose"); const productSchema = new Schema( { productCode: { type: Schema.Types.ObjectId, default: () => new Types.ObjectId(), }, productDescription: { type: String, required: true, maxlength: 350, }, productMediaType: { type: String, enum: ['Photo', 'Video'] }, productMediaFile: { type: String, maxlength: 80, }, username: { type: String, }, createdAt: { type: Date, default: Date.now, }, }, { toJSON: { getters: true, }, } ); const orderSchema = new Schema( { orderCode: { type: String, //required: true, maxlength: 280, }, orderDescription: { type: String, required: true, maxlength: 350, }, createdAt: { type: Date, default: Date.now, }, username: { type: String, }, products: [productSchema], }, { toJSON: { virtuals: true, getters: true, }, id: false, } ); const Order = model("Order", orderSchema);
需求解决方案
a) 查询特定客户的所有完整订单信息
有两种常用实现方式:
方式1:使用 Mongoose 的 populate 方法
直接查询目标客户时,关联填充orders字段的完整订单数据:
// 可通过username、_id、email等唯一标识定位客户 const customerWithOrders = await Customer.findOne({ username: "目标用户名" }) .populate("orders"); // 自动填充orders数组中ObjectId对应的完整Order文档 // 提取完整订单列表 const customerOrders = customerWithOrders.orders;
方式2:分步查询
先获取客户的订单ID数组,再批量查询订单:
// 第一步:获取目标客户的订单ID数组 const customer = await Customer.findOne({ username: "目标用户名" }, "orders"); // 第二步:根据ID数组查询所有完整订单 const customerOrders = await Order.find({ _id: { $in: customer.orders } });
b) 查询Orders集合中包含的所有商品
由于商品是嵌套在Order文档中的子文档,使用MongoDB聚合管道提取所有商品:
const allProducts = await Order.aggregate([ // 拆分每个订单的products数组,每个商品成为独立文档 { $unwind: "$products" }, // 将子文档提升为根文档,仅保留商品数据 { $replaceRoot: { newRoot: "$products" } }, // 可选:去重(排除重复productCode的商品) { $group: { _id: "$productCode", product: { $first: "$$ROOT" } } }, { $replaceRoot: { newRoot: "$product" } } ]);
如果不需要去重,可去掉最后两步聚合阶段,直接返回拆分后的所有商品文档。
内容的提问来源于stack exchange,提问作者WizzyOlammie
相关产品推荐
相关产品推荐

