-1

I have two models:

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' }],
});

and

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}
});

and I want get the mount of the wallet (amountStart - all mount of transfers)

but I'm not sure how to do it, thanks!

Rpv
  • 1
  • 3

2 Answers2

0

The easiest way to do this would be an aggregation.

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" ] } } }
])

I haven't tested it, but if you understand each step, you should be fine.

BenSower
  • 1,532
  • 1
  • 13
  • 26
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"}]}}
   ])
Rpv
  • 1
  • 3