我有两个模型:
const walletSchema = mongoose.Schema({
title: { type: String, required: true },
description: { type: String, required: false},
amountStart: { type: Number, required: true},
mount: {type: Number, required: false},
transfers: [{ type: Schema.Types.ObjectId, ref:'Transfers' }],
});
和
const transferSchema = mongoose.Schema({
mount: { type: Number, required: true },
category_id: { type: Schema.ObjectId, ref: "Category", required: false },
description: { type: String, required: false},
wallet_id: { type: mongoose.Schema.Types.ObjectId, ref:"Wallet", required: true}
});
我想获得钱包的挂载(amountStart-所有转账的挂载)
但是我不确定该怎么做,谢谢!
答案 0 :(得分:0)
最简单的方法是聚合。
walletSchema.aggregate([
// finds your wallet
{$match : {_id: <theIdOfYourWallet}},
// splits your array into multiple aggregation documents
// (see this for more info: https://stackoverflow.com/questions/34967482/lookup-on-objectids-in-an-array)
{$unwind: 'transfers'},
// fetches each transfer document
{ $lookup: {
from: "transfers",
localField: "transfers",
foreignField: "_id",
as: "transferInformation"
}},
// sums the transfers
{ $group:
{
_id: { amountStart: $amountStart },
// not sure if you can access the .mount field directly like this
totalTransferMount: { $sum: $transferInformation.mount },
}
},
// calculating the total mount of the wallet
{ $project: { walletMount: { $subtract: [ "$_id.amountStart", "$totalTransferMount" ] } } }
])
我还没有测试过,但是如果您理解了每个步骤,就可以了。
答案 1 :(得分:0)
walletSchema.aggregate([
{ "$match": { "_id": <theIdOfYourWallet } },
{ $lookup: {
from: "transfers",
localField: "transfers",
foreignField: "_id",
as: "transferInformation"
}},
{ $project: {walletMount: {$sum: "$transferInformation.mount"}, amountStart: "$amountStart", transfers:[{transfer:"$transferInformation"}]}}
])