我想知道是否有更好的方法来检查数据库,如果我要插入的记录存在以避免重复。这样我就可以插入只有UNIQUE的记录。
现在我所做的是用于通过if语句进行原始查询来检查数据库,以及它是否通过我插入记录的条件:
const addName = function(name, amount) {
sequelize.query(`SELECT * FROM names WHERE name="${name}"`, { type: sequelize.QueryTypes.SELECT})
.then(names => {
if (names.length === 0) {
sequelize.query(
`INSERT INTO names (name, amount) VALUES('${name}','${amount}')`, {
type: Sequelize.QueryTypes.INSERT
}
).then(function (data) {
console.log('inserted STEAMER data---> ', data);
});
} else {
console.log('Duplicate records >>>>>>');
}
});
};
有没有替代方法可以通过Sequelize JS做到这一点?
答案 0 :(得分:2)
我认为你要使用Sequelize的ORM方式,只需在模型上调用findOrCreate
方法。
示例:
1)db.js
:
const Sequelize = require('sequelize');
const sequelize = new Sequelize('mysql://user:pass@127.0.0.1:3306/dbname');
const Name = sequelize.define('Name', {
name: {
type: Sequelize.STRING,
allowNull: false,
unique: true
},
amount: {
type: Sequelize.DECIMAL(10, 2), // or .INTEGER
allowNull: false,
defaultValue: 0
}
}, {
tableName: 'names',
timestamps: false,
freezeTableName: true
});
// extending model with method
Name.upsert = (name, amount) => {
const find = {name};
const create = {name, amount};
return Name.findOrCreate({where: find, defaults: create});
};
module.exports = {sequelize, models: {Name}};
2)app.js
(在快递示例中):
const db = require('./db');
const Name = db.models.Name;
app.post('/names', async (req, res) => {
try {
const name = req.body.name;
const amount = req.body.amount;
const result = await Name.upsert(name, amount);
res.status(200).send(result);
}
catch (error) {
res.status(500).send(error);
}
});
阅读this getting started并使用即时使用Sequelize ORM的方法保存您的一天