gpt4 book ai didi

node.js - Nodejs Sequelize beforeCreate 钩子(Hook)做一些验证

转载 作者:太空宇宙 更新时间:2023-11-04 02:24:33 25 4
gpt4 key购买 nike

在数据库中插入新记录之前,我需要执行一些检查,然后决定是否可以插入该记录。我想使用 beforeCreate 钩子(Hook)做这样的事情:

    Data.beforeCreate(function(object, options) {
Data.scope('complexQuery').findAll().then(function (result) {
if (result.length >= 1) {
// do not insert the record
}
else {
// go ahead and insert
}
});
});

关于如何停止创建记录有什么想法吗?

这是正确的方法吗?

最佳答案

您可以抛出错误,或拒绝 promise :

    Data.beforeCreate(function(object, options) {
Data.scope('complexQuery').findAll().then(function (result) {
if (result.length >= 1) {
throw new Error('Already exists')
return sequelize.Promise.reject('Already exists')
}
else {
// go ahead and insert
}
});
});

由于您实际上正在进行验证,因此它可能更适合作为验证函数:)

sequelize.define('model', attributes, {
validate: {
complexQuery: function () {
// Do the validation here instead
}
}
});

创建和更新都会运行验证

关于node.js - Nodejs Sequelize beforeCreate 钩子(Hook)做一些验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31321117/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com