我有一个cat Owl 模型:
/** USER MODEL */
const UserSchema = new mongoose.Schema(
{
username: {
type: String,
unique: true,
},
password: {
type: String,
min: 5
},
wallets: [{
name: {
type: String,
required: true
},
balance: {
type: Number,
required: true
}
}],
transactions: [{
type: {
type: String,
enum: ['expense', 'income']
},
label: {
type: String,
required: true
},
amount: {
type: Number,
required: true
},
category: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
},
wallet: {
type: String,
required: true
}
}],
},
{ timestamps: true }
)
** THE CONTROLLER **
export const addTransaction = async (req, res) => {
try {
const { id } = req.params;
const transaction = req.body.transaction
const user = await User.findById(id)
console.log(transaction.wallet)
const wallet = await User.find(
{ "wallets.name": transaction.wallet })
console.log(wallet)
await User.findByIdAndUpdate(id, { $push: { transactions:
transaction } })
res.status(200).json(user);
} catch (err) {
res.status(404).json({ message: err.message });
}
}
req.body.transaction具有:
- 要减go 钱包余额的金额//交易金额
- 标签//钱包计算中不需要
- wallet //需要访问以更改其余额的钱包的名称
当一笔交易完成时,我会得到金额.然后我需要从钱包余额中减go 这笔钱.通过req.body,我得到了walletname和金额.
我需要一个Mongoose查询来查找User.wallets中的钱包并编辑其余额.
我已经try 过findByIdAndUpdate、Find、findOne、findbyID、$Set:
User.findByIdAndUpdate(id, {$set: {"wallets.amount": transaction.amount}})
User.findByIdAndUpdate(id, { wallets: { name: transaction.wallet { amount: transaction.amount} }})
我在上面的控制器中使用的User.find函数也返回整个用户,但Wallet是:[[Object],[Object]]
但我觉得我用得不对.