【问题标题】:Access the properties of the relationship -- MongoDb访问关系的属性——MongoDb
【发布时间】:2023-04-01 05:35:01
【问题描述】:

我有两个模型:

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 - 所有转账挂载)

但我不知道该怎么做,谢谢!

【问题讨论】:

    标签: angular mongodb express mongoose mean


    【解决方案1】:

    最简单的方法是聚合。

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

    我没有测试过,但是如果你理解了每一步,你应该没问题。

    【讨论】:

    • 我用这个解决了:walletSchema.aggregate([ { "$match": { "_id":
    • 这是正确的,甚至更优雅。从 Mongodb 3.2 开始,$sum 运算符也可以在项目中使用
    【解决方案2】:
    walletSchema.aggregate([
        { "$match": { "_id": <theIdOfYourWallet } },
        { $lookup: {
           from: "transfers",
           localField: "transfers",
           foreignField: "_id",
           as: "transferInformation"
         }},
         { $project: {walletMount: {$sum: "$transferInformation.mount"}, amountStart: "$amountStart", transfers:[{transfer:"$transferInformation"}]}}
       ])
    

    【讨论】:

      猜你喜欢
      • 2015-11-22
      • 2020-02-08
      • 2018-08-12
      • 1970-01-01
      • 2018-06-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 2020-07-04
      相关资源
      最近更新 更多