Reputation: 11
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
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