mysql - 如何使用 sequelize 在 nodejs 中更新
问题描述
当我在钱包中存入金额时,我想更新钱包表。
我的代码是这样的:
模型 wallet.js
'use strict';
module.exports = (sequelize, DataTypes) => {
var Model = sequelize.define('wallet', {
id: {
type: DataTypes.INTEGER,
field: 'id',
primaryKey: true,
autoIncrement: true
},
cid: {
type: DataTypes.STRING,
field: 'cid'
},
deposit: {
type: DataTypes.INTEGER,
field: 'deposit'
},
withdrawal: {
type: DataTypes.INTEGER,
field: 'withdrawal'
},
available: {
type: DataTypes.INTEGER,
field: 'available',
},
comments: {
type: DataTypes.DATE,
field: 'comments'
},
online: {
type: DataTypes.STRING,
field: 'online'
}
}, {
tableName: 'wallet',
timestamps: false
});
Model.associate = function (models) {
this.orders = this.hasOne(models.orders, {
as: 'orders',
foreignKey: 'wid'
});
};
Model.prototype.toWeb = function (pw) {
let json = this.toJSON();
return json;
};
return Model;
};
这里钱包存款发生在这里我正在使用 set 方法来更新钱包
walletcontroller.js
const deposit = async function (req, res) {
res.setHeader('Content-Type', 'application/json');
let err, wallet, existingWallet;
let wallet_info = req.body;
[err, existingWallet] = await to(Wallet.findAll({
limit: 1,
where: {
cid: wallet_info.cid,
},
order: [
['id', 'DESC']
]
}));
[err, wallet] = await to(Wallet.set(wallet_info, {
limit: 1,
where: {
cid: wallet_info.cid,
},
order: [
['id', 'DESC']
]
}));
if (err) return ReE(res, err, 422);
if (existingWallet[0] != 'undefined') {
wallet.available = existingWallet[0].available + wallet_info.deposit;
wallet.comments = new Date();
} else {
wallet.available = wallet_info.deposit;
wallet.comments = new Date();
}
console.log("avalible balance:" + wallet.available);
[err, wallet] = await to(wallet.save());
if (err) return ReE(res, err, 422);
return ReS(res, {
wallet: wallet.toWeb()
}, 201);
}
module.exports.deposit = deposit;
请帮助我如何更新钱包......当我在这里调用 api 时,我的错误消息看起来像这样
Executing (default): SELECT `id`, `cid`, `deposit`, `withdrawal`, `available`, `comments`, `online` FROM `wallet` AS `wallet` WHERE `wallet`.`cid` = '33' ORDER BY `wallet`.`id` DESC LIMIT 1;
错误:
Uncaught Error { filename: '\\cl-api-master\\controllers\\WalletController.js',
line: 67,
row: 37,
message: 'Wallet.set is not a function',
type: 'TypeError',
stack: 'TypeError: Wallet.set is not a function\n at deposit (E:\\cl-api-master\\controllers\\WalletController.js:67:37)\n at <anonymous>',
arguments: undefined }
POST /v1/wallet/deposit - - ms - -
解决方案
对于版本,您可以简单地使用 -
data.update = await Wallet.update(
{
available: available,
comments: new Date()
},
{
where: { cid: wallet_info.cid }
}
);
在更新查询上面运行之后,可以使用 if else 条件设置可用变量。
推荐阅读
- ios - Apple Wallet 通过竞争
- servicestack - ServiceStack.OrmLite:写/读慢?
- node.js - 将其他文件夹中的 nodejs 模块包含到项目文件夹中
- c# - 在 C# 中使用多个字段对 ListBox 进行排序
- django - 如何使用 ORDER BY Chinese USERNAME 查询(转换为 gbk?) - Django,psql
- java - 即使在新项目中,几个小时后也无法扩展 RecyclerView.Adapter
- javascript - 使用 cordova 文件传输附加 pdf/word 文件
- python - 反向访问python中的列表
- android - 再次从列表中删除项目后,它即将到来
- r - 矩阵分解中产生的 NaN