【问题标题】:Sequelize "object" does not have increment function续集“对象”没有增量功能
【发布时间】:2021-09-28 17:55:12
【问题描述】:

我在我的项目中使用 Django 生成的模型和 sequelize-auto 生成续集表。到目前为止,一切都很好。如果我再次看到一个 url,我编写了代码来更新排名。

const findLink = async (link) =>
  Link.findOne({
    where: {
      url: link,
    },
    raw: true,
  });
// eslint-disable-next-line no-use-before-define
const insertEvent = async (link, tweetText) => {
  // Sync Database table before reading
  await sequelize.sync();
  findLink(link).then((url) => {
    if (url) {
      url.increment("rank", {by: 1}).then(()=>{
      Event.create({
        url_id: url.id,
        tweet_text: tweetText,
        created_at: new Date(),
        updated_at: new Date(),
      })
    });

    } else {
      Link.create({
        url: link,
        rank: 0,
        created_at: new Date(),
        updated_at: new Date(),
      }).then((newLink) => {
        Event.create({
          url_id: newLink.id,
          tweet_text: tweetText,
          created_at: new Date(),
          updated_at: new Date(),
        });
      });
    }
  });
};

但问题是,当它执行url.increment("rank", {by: 1}) 时,它说url 没有increment 功能。

但根据文档,它明确指出here。如果我做错了什么,请告诉我?我已经搜索了互联网,但我找不到任何相关的东西。我可以通过重复查找来更新值,但我正在寻找一种方法,如果我可以更新已经找到的对象而不是再次搜索它。

【问题讨论】:

    标签: javascript sequelize.js


    【解决方案1】:

    您正在使用原始查询

    const findLink = async (link) =>
      Link.findOne({
        where: {
          url: link,
        },
        raw: true,
      });
    

    它不返回模型的实例

    https://sequelize.org/master/manual/raw-queries.html

    编辑:

    默认情况下,该函数将返回两个参数 - 一个结果数组和一个包含元数据(例如受影响的行数等)的对象。

    第二个选项是模型。如果您传递模型返回的数据 将是该模型的实例。

    // Callee is the model definition. This allows you to easily map a query to a predefined model
    const projects = await sequelize.query('SELECT * FROM projects', {
      model: Projects,
      mapToModel: true // pass true here if you have any mapped fields
    });
    // Each element of `projects` is now an instance of Project
    

    所以 mapToModel 选项也可能起作用

    【讨论】:

    • @foragerDev 已编辑
    • 谢谢,删除raw:true 成功了。
    • @foragerDev 很高兴听到它成功了!
    猜你喜欢
    • 2011-08-14
    • 1970-01-01
    • 1970-01-01
    • 2016-09-15
    • 2020-12-18
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多