汇总然后更新到其他集合

时间:2020-10-27 07:58:25

标签: javascript node.js mongodb mongoose

我想将我的集合(控制器函数)的返回数据插入另一个名为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);

我想将此控制器函数的结果作为另一个变量插入到用户集合中

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,但它代替了整个用户集合。

我只希望它添加到特定用户并在每次使用上述控制器功能时更新其内容。谢谢!

1 个答案:

答案 0 :(得分:0)

Traceback (most recent call last):
  File "U:\GSY\scipt.py", line 14, in <module>
    df['S'] = df.apply(lambda x: my_func(x['E'], x['I']),axis=1).map(lambda x: x[0])
  File "C:\Users\gsy.LSH\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\pandas\core\series.py", line 3630, in map
    new_values = super()._map_values(arg, na_action=na_action)
  File "C:\Users\gsy.LSH\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\pandas\core\base.py", line 1145, in _map_values
    new_values = map_f(values, mapper)
  File "pandas\_libs\lib.pyx", line 2329, in pandas._libs.lib.map_infer
  File "U:\GSY\script.py", line 14, in <lambda>
    df['S'] = df.apply(lambda x: my_func(x['E'], x['I']),axis=1).map(lambda x: x[0])
TypeError: 'int' object is not subscriptable

我可以使用findByIdAndUpdate()和$ set运算符将totalIncome添加到我的用户集合中。请随时为我的上述问题提供其他解决方案。