Mongoose Aggregation with Match pipeline operator using an Object Id
JS
S
JavaScriptSimple example of using an aggregation with match pipeline operators for an ID. Please note that an aggregation always returns an array. Requirements: Mongoose > 4, Bluebird as promise library
1const accountId = 'random';
2// Account.subscriptions: [{...}]
3
4const updateFields = {
5 $set: {
6 cancelReason: 'Automated cleanup.',
7 cancelled: true
8 }
9};
10
11const options = { new: true };
12return Account.aggregate()
13 .match({ '_id': ObjectId(accountId) })
14 .project({
15 lastSubscription: { $arrayElemAt: ['$subscriptions', -1] }
16 })
17 .limit(1)
18 .exec()
19 .then(result => {
20 if(result.length > 0){
21 const resultData = result[0];
22 const subscriptionId = resultData.lastSubscription;
23 return Subscription.findByIdAndUpdate(subscriptionId, updateFields, options)
24 }
25 })Created on 4/5/2018