如果值不存在,如何不更新列 sequelize

how to not update column if value is not present sequelize

我有一个客户 table,它在 sequelize mysql

中包含几列和 password

当我 edit/update 客户时,如果用户未在请求中提供密码,则根本不应更新密码列(应保持不变)。

如何在客户模式页面中完成这样的程序?

我正在使用以下方法更新 table:


db.customers.findOne({
    where: {
        id: req.body.id
    }
}).then(data => {
    data.update({
        cash_credit: req.body.cash_credit,
        name: req.body.name,
        address: req.body.address,
        state_id: req.body.state_id,
        gstin: req.body.gstin,
        mobile: req.body.mobile,
        phone: req.body.phone,
        email: req.body.email,
        form_type: req.body.form_type,
        pincode: req.body.pincode,
        password: req.body.password, // omit
        city_id: req.body.city_id,
        country: req.body.country || 0,
        id: req.body.id
    }).then(data2 => {
        console.log(data2);
    });
});

这是我的客户架构:

const bcrypt = require("bcrypt");
module.exports = function (sequelize, DataTypes) {
    const customers = sequelize.define("customers", {
        id: {
            type: DataTypes.INTEGER,
            primaryKey: true,
            autoIncrement: true,
            field: "SupplierCode"
        },
        customer_type: {
            type: DataTypes.INTEGER,
        },
        cash_credit: {
            type: DataTypes.STRING,
        },

        ...

    }, {
        hooks: {
            // eslint-disable-next-line no-unused-vars
            beforeValidate: function (value, option) {
                value.zip = parseInt(value.dataValues.zip);
            },
            beforeCreate: async (schema) => {
                let hashedPassword = await bcrypt.hash(schema.password, saltRounds);
                schema.password = hashedPassword;
                console.log(schema.password);
            },
            beforeUpdate: async (schema) => {
                if (schema.password) {
                    let hashedPassword = await bcrypt.hash(schema.password, saltRounds);
                    schema.password = hashedPassword;
                }
            }
        },
        timestamps: false,
        defaultScope: {
            attributes: {
                exclude: ["password"]
            }
        },
        scopes: {
            withPassword: {
                attributes: {
                    include: ["password"]
                }
            }
        }
    });
}

据我所知,Sequelize 不会更新您未提供的字段。因此,如果未定义 password,则不要将其传递给 update 调用。

const updateData = {
    cash_credit: req.body.cash_credit,
    name: req.body.name,
    address: req.body.address,
    state_id: req.body.state_id,
    gstin: req.body.gstin,
    mobile: req.body.mobile,
    phone: req.body.phone,
    email: req.body.email,
    form_type: req.body.form_type,
    pincode: req.body.pincode,
    city_id: req.body.city_id,
    country: req.body.country || 0,
    id: req.body.id
}

if (req.body.password) {
   updateData.password = req.body.password;
}

data.update(updateData).then(console.log);