我试着加入两个模式并总结总价。 这是一个架构:
const Product = new mongoose.Schema({
name: { type: String, required: true },
price: Number
})
const Order = new mongoose.Schema({
fullname: { type: String, required: true },
address: { type: String, required: true },
products: [
{
product: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Product',
},
quantity: Number,
},
],
})
我想创建聚合,以获得总价格的订单。所以它可以像:
[
{
fullname: 'jhon doe',
address: 'NY 1030',
products: [
{
product: {
name: 'Piano',
price: 50
},
quantity: 10,
},
],
price: 500
}
]
我尝试使用聚合框架没有任何成功,有什么想法吗?
您可以在聚合中使用$LOOKUP,如下所示:
db.getCollection('orders').aggregate([{
$lookup:
{
from: "products",
localField: "products.product",
foreignField: "_id",
as: "p"
}},
{$unwind:{path:"$p"}},
{
$project:{
"fullname" : 1,
"address" : 1,
"products" :
{
"product" : "$p",
"quantity" : 1
},
"price" : 1
}
} ])