nodejs sequelize beforeCreate 钩子做一些验证
nodejs sequelize beforeCreate hook to do some validation
在数据库中插入新记录之前,我需要执行一些检查,然后决定是否可以插入该记录。
我想使用 beforeCreate 钩子做这样的事情:
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
}
});
});
知道如何停止创建记录吗?
这样做正确吗?
您可以抛出错误,也可以拒绝承诺:
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
}
}
});
创建和更新的验证都是运行
在数据库中插入新记录之前,我需要执行一些检查,然后决定是否可以插入该记录。 我想使用 beforeCreate 钩子做这样的事情:
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
}
});
});
知道如何停止创建记录吗?
这样做正确吗?
您可以抛出错误,也可以拒绝承诺:
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
}
}
});
创建和更新的验证都是运行