![](/img/trans.png)
[英]Aggregate data from Mongo collection based on dates and other fields, and count
[英]aggregate then update to other collection
我想將聚合(控制器函數)的返回數據插入到另一個名為 User 的集合中。 以下是我的用戶模式:
const userSchema = new mongoose.Schema({ firstName: { type: String, required: [true, 'First name is required'] }, lastName: { type: String, required: [true, 'Last name is required'] }, email: { type: String, required: [true, 'Email is required'] }, loginType: { type: String, required: [true, 'Login type is required'] }, password: { type: String }, transactions: [{transactionId: String}, date:{type:Date, default:new Date()}], totalIncome: [{id:String},{totalIncome:Number}] }) module.exports = mongoose.model('User', userSchema);
我想將這個 controller function 的結果作為另一個變量插入到用戶集合中
return Transaction.aggregate([ { $match : { userId : userId, type:"Income",isActive:true} }, {
$group: {
_id: "$type",
totalIncome: {
$sum: "$amount"
}
}
}
]).then((totalIncome,err)=> {
return (err) ? false : totalIncome
})
我上面的聚合結果是這樣的:
[
{
"_id": "Income",
"totalIncome": 18000
}
]
請幫助:( 我嘗試添加$out
但它替換了整個用戶集合。
我只想讓它添加到特定用戶並在每次使用上面的 controller function 時更新其內容。 謝謝!
return Transaction.aggregate([ { $match : { userId : userId, type:"Income",isActive:true} }, {
$group: {
_id: "$type",
amount: {
$sum: "$amount"
}
}
}
]).then((totalIncome,err)=> {
// return (err) ? false : totalIncome
console.log(totalIncome)
if (err) {
return false
} else {
User.findByIdAndUpdate(userId, {"$set" : {"totalIncome": totalIncome[0].amount }}, { "new": true })
.then((transaction, err ) => {
return (err) ? false : true
})
}
})
通過使用 findByIdAndUpdate() 和 $set 運算符,我能夠將 totalIncome 添加到我的用戶集合中。 請隨時為我的上述問題提供不同的解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.