在Sequelize中插入来自JSON数组的多条记录可以通过以下步骤实现:
const { Sequelize, DataTypes } = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: 'mysql',
});
const MyModel = sequelize.define('MyModel', {
name: {
type: DataTypes.STRING,
allowNull: false,
},
age: {
type: DataTypes.INTEGER,
allowNull: false,
},
// 其他字段...
});
sequelize.sync(); // 同步模型与数据库
const records = [
{ name: 'John', age: 25 },
{ name: 'Jane', age: 30 },
// 其他记录...
];
bulkCreate
方法将JSON数组中的记录插入到数据库中。MyModel.bulkCreate(records)
.then(() => {
console.log('插入成功!');
})
.catch((error) => {
console.error('插入失败:', error);
});
在上述代码中,bulkCreate
方法将会批量插入JSON数组中的记录到数据库中。插入成功后,将会打印出"插入成功!"的消息。如果插入失败,将会打印出错误信息。
请注意,上述代码中的数据库连接配置是示例,你需要根据自己的实际情况进行修改。
推荐的腾讯云相关产品:腾讯云数据库MySQL、腾讯云云服务器CVM。
腾讯云数据库MySQL产品介绍链接地址:https://cloud.tencent.com/product/cdb
腾讯云云服务器CVM产品介绍链接地址:https://cloud.tencent.com/product/cvm
领取专属 10元无门槛券
手把手带您无忧上云