Sequelize查询返回的对象不存在increment方法如何解决?
问题解答
错误原因
你在调用Link.findOne时添加了raw: true配置,该配置会让Sequelize直接返回纯JSON格式的查询结果,而非Sequelize模型的实例对象,因此不具备increment这类模型实例内置方法。
可行实现方案
方案1:移除raw: true获取模型实例(适配你的需求,无额外二次查询)
直接修改findLink方法,去掉raw: true配置即可拿到完整的模型实例,实例的increment方法底层只会基于实例主键生成UPDATE语句,不会触发二次查询,完全符合你的要求。
修改后的参考代码如下:
// 移除raw: true配置,返回模型实例 const findLink = async (link) => Link.findOne({ where: { url: link, }, }); const insertEvent = async (link, tweetText) => { await sequelize.sync(); const existLink = await findLink(link); const currentTime = new Date(); if (existLink) { // 仅执行1次UPDATE语句,无额外查询 await existLink.increment("rank", { by: 1 }); await Event.create({ url_id: existLink.id, tweet_text: tweetText, created_at: currentTime, updated_at: currentTime, }); } else { const newLink = await Link.create({ url: link, rank: 0, created_at: currentTime, updated_at: currentTime, }); await Event.create({ url_id: newLink.id, tweet_text: tweetText, created_at: currentTime, updated_at: currentTime, }); } };
方案2:使用静态increment方法(性能更高,适合不需要提前获取实例的场景)
直接调用模型的静态increment方法,将查询和更新合并为单条SQL语句执行,仅返回受影响的行数,适合不需要提前获取链接实例的场景:
const insertEvent = async (link, tweetText) => { await sequelize.sync(); const currentTime = new Date(); // 单条SQL完成匹配+增量更新,返回受影响行数 const [updateCount] = await Link.increment("rank", { where: { url: link }, by: 1, }); let linkId; if (updateCount > 0) { // 存在匹配链接,查询对应ID用于创建Event const existLink = await Link.findOne({ where: { url: link }, attributes: ["id"] }); linkId = existLink.id; } else { // 不存在匹配链接,创建新链接 const newLink = await Link.create({ url: link, rank: 0, created_at: currentTime, updated_at: currentTime, }); linkId = newLink.id; } await Event.create({ url_id: linkId, tweet_text: tweetText, created_at: currentTime, updated_at: currentTime, }); };
内容的提问来源于stack exchange,提问作者foragerDev
相关产品推荐
相关产品推荐

