Node.js 在保存钩子不开火之前进行续集
我已经使用sequelize auto生成了模型,需要使用beforeSave挂钩(请参阅)。据我所知,鱼钩没有开火。sequelize版本^4.20.1,sequelize自动版本^0.4.29,express版本~4.15.5。有人能帮忙吗Node.js 在保存钩子不开火之前进行续集,node.js,postgresql,sequelize.js,postgis,Node.js,Postgresql,Sequelize.js,Postgis,我已经使用sequelize auto生成了模型,需要使用beforeSave挂钩(请参阅)。据我所知,鱼钩没有开火。sequelize版本^4.20.1,sequelize自动版本^0.4.29,express版本~4.15.5。有人能帮忙吗 module.exports = function(sequelize, DataTypes) { return sequelize.define('trad', { id: { type: DataTypes.INTEGER,
module.exports = function(sequelize, DataTypes) {
return sequelize.define('trad', {
id: {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
geom: {
type: DataTypes.GEOMETRY('POINT', 4326),
allowNull: true
},
...
}, {
hooks: {
beforeSave: (instance, options) => {
console.log('Saving geom: ' + instance.geom);
if (instance.geom && !instance.geom.crs) {
instance.geom.crs = {
type: 'name',
properties: {
name: 'EPSG:4326'
}
};
}
}
},
tableName: 'trad',
timestamps: false,
});
};
以下是PUT请求的代码:
// Update (PUT)
router.put('/table/:table/:id', function(req, res, next) {
db.resolveTableName( req )
.then( table => {
const primaryKey = table.primaryKeyAttributes[0];
var where = {};
where[primaryKey] = req.params.id;
console.log('Put - pkey: ' + primaryKey);
auth.authMethodTable( req )
.then( function() {
table.update( req.body, {
where: where,
returning: true,
plain: true
})
.then( data => {
res.status(200).json( data[1].dataValues );
})
.catch( function (error ) {
res.status(500).json( error );
});
})
.catch( function( error ) {
res.status(401).json('Unauthorized');
});
})
.catch( function(e) {
res.status(400).json('Bad request');
});
});
除非指定,否则,
beforeSave
钩子将为单个模型实例触发,但不会为批量更新触发。在您的情况下,您有两种选择之一:
(1) 将individualHooks
传递到您的查询:
table.update( req.body, {
where: where,
returning: true,
individualHooks: true
plain: true
})
(2) 在更新之前获取模型实例:
table.findById(req.params.id)
.then(function(instance) {
instance.update(req.body, {
returning: true
plain: true
})
})
除非指定,否则,
beforeSave
钩子将为单个模型实例触发,但不会为批量更新触发。在您的情况下,您有两种选择之一:
(1) 将individualHooks
传递到您的查询:
table.update( req.body, {
where: where,
returning: true,
individualHooks: true
plain: true
})
(2) 在更新之前获取模型实例:
table.findById(req.params.id)
.then(function(instance) {
instance.update(req.body, {
returning: true
plain: true
})
})
你能分享你试图保存模型实例的代码吗?好主意@mcranston18。完成!你能分享你试图保存模型实例的代码吗?好主意@mcranston18。完成!谢谢@mcranston18。我使用了选项2,因为这似乎是更新单个记录的更干净的方法。鱼钩正在开火。另外,在选项2中,sequelize似乎只保存更改的属性-加上几何体,因为我已经添加了钩子。谢谢@mcranston18。我使用了选项2,因为这似乎是更新单个记录的更干净的方法。鱼钩正在开火。另外,在选项2中,sequelize似乎只保存更改的属性-加上我添加了挂钩后的几何体。