Call function inside mongodb's aggregate?

后端 未结 3 1717
一个人的身影
一个人的身影 2020-11-30 14:26

Collection:

[
    { _id: \"Foo\", flag1: false, flag2: true, flag3: false },
    { _id: \"Bar\", flag1: true, flag2: false, flag3: true }
]

3条回答
  •  心在旅途
    2020-11-30 15:06

    The aggregate call can be passed a callback function, which is called after the aggregation has completed.

    function getValuesAndMessges( params, callback ) {
    
      db.collection.aggregate([
        { "$project": {
           "_id": 1,
           "flag1": { "$first": "$flag1" },
           "flag2": { "$first": "$flag2" },
           "flag3": { "$first": "$flag3" },
        }}
      ], function( err, results ) {
        if ( !err ) {
          result.forEach( result => {
            // process items in results here, setting a value
            // using the actual logic for writing message ...
            if( flag1 )
              result.message = "broken";
            else
              result.messsge = 'OK';
          });
        }
        callback(err, results);
      });
    }
    

    this way each of your aggregated items (based on your conditions / parameters) will have a message property (or whatever properties you choose to write) set and you can use them in your calling function.

提交回复
热议问题