Sequelize "object" 没有自增功能

Sequelize "object" does not have increment function

我在我的项目中使用 sequelize-auto 从 Django 生成的模型生成 sequelize 表。到目前为止,一切都很好。如果我再次看到 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。如果我做错了什么,请告诉我?我在网上搜索过,但找不到任何相关的东西。我可以通过重复查找来更新值,但我正在寻找一种方法,如果我可以更新已经找到的对象而不是再次搜索它。

您正在使用原始查询

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

它不是return模型的实例

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

编辑:

By default the function will return two arguments - a results array, and an object containing metadata (such as amount of affected rows, etc).

A second option is the model. If you pass a model the returned data will be instances of that model.

// 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 选项也可能有效