在Mongoose

时间:2017-07-29 11:48:38

标签: node.js mongodb mongoose

如果没有匹配我获得了所需的输出,当我提供$ match值时,我得到一个空的响应。空洞反应的原因是什么?是否有任何不同的方式来调用$ match param?

var query = {"section":"324444"};  // 324444 is section schema _id value 


Transaction.aggregate({
"$match": query
},{ "$group": { "_id": "$user", "section": { "$first": "$section"}, "amount": { "$sum": { "$cond": ["$credit", "$amount", { "$subtract": [ 0, "$amount" ] }] }} }})
      .exec(function(err, transactions)
       {
              // Transactions List Grouped User wise 
        });

// Transaction schema
 var transSchema = new Schema({
  user: {type: mongoose.Schema.Types.ObjectId, ref: 'User',required: true},
  section: {type: mongoose.Schema.Types.ObjectId, ref: 'Section',required: true},
  amount: { type: Number, required: true},
  credit: { type: Boolean, default: true }
  created_at: Date
});         

// Section schema
var sectionSchema = new Schema({
  name: { type: String, required: true},
  created_at: Date
}); 

更新: 试过下面的代码,但我得到空的回应。另外,当我必须匹配来自2个或更多个集合时,我该如何处理(例如,我说另一个名为SubSection的集合类似于事务模式中的Section)

代码:

      Transaction.aggregate({ "$lookup": {
      "from": Section.collection.name,
      "localField": "section",
      "foreignField": "_id",
      "as": "section"
    }},
    { "$match": {"section._id":"324444"} },
    { "$group": { "_id": "$user", "section": { "$first": "$section"}, "amount": { "$sum": { "$cond": ["$credit", "$amount", { "$subtract": [ 0, "$amount" ] }] }} }})
      .exec(function(err, transactions)
       {

           // Results 

        });

0 个答案:

没有答案