sdkamath7
sdkamath7

Reputation: 11

How to get documents count returned by Model.countDocuments() function and set it to some other field in mongoose

I would like to SET ($set) the total 'count' returned by the below mongoose function to some other field in the different mongodb collection while updating(update query) the collection.

// Get count from User collection

   User.countDocuments({age:{$gte:5}}, function (err, count) { 
       if (err){ 
            console.log(err) 
        }else{ 
            console.log("Count :", count) 
        } 
    }); 

//Set count to the field viewCount in the StatChartMonitor collection as below

var user_id = '5e218e6811a54db030ff8f7b'; 
StatChartMonitor.findByIdAndUpdate(user_id, { viewCount: count}, 
function(err, docs) { 
    if (err){ 
       console.log(err) 
    } 
    else{ 
        console.log("Updated User : ", docs); 
    } 
}); 

Is there any way in mongoose to get that count(integer) value and set it in the update query ?

Upvotes: 0

Views: 452

Answers (1)

Mze
Mze

Reputation: 187

async function countAndUpdate() {
  const count = await User.countDocuments({age:{$gte:5}}

  await StatChartMonitor.findByIdAndUpdate(id, { $set: { viewCount: count } })
}

You need to add the keywords async and await in order to wait a Promise to be executed and access countDocuments result.

After that, you can findByIdAndUpdate with $set

Upvotes: 0

Related Questions