【问题标题】:Add ordinal suffix if a record already exists in node js如果节点js中已经存在记录,则添加序号后缀
【发布时间】:2020-11-21 05:52:22
【问题描述】:

现在当文件已经存在时,我添加了前缀,它是文件名的时间戳以使其唯一。

但我想实现一个序数后缀。所以如果我添加一个带有文件名的文件,例如 helloworld 并且该文件存在,那么新文件名现在将是 helloworld-1st,然后如果我再次添加它将是 helloworld-2nd 等等。任何人都知道如何实现这一点?下面的查询已经用于检查记录。谢谢。

例如,数据库中有一个文件名为 hello 的 existine 文件。

如果我添加一个带有 hello 的文件名,那么现在的新文件名将是 hello-1st。 然后我再次添加文件名为 hello 的文件,所以现在的新文件名是 hello-2nd ,如果我再次添加 hello ,新的文件名现在将是 hello-3rd 等等。

#code 检查文件是否已经存在

 const file = await context.service.Model.findOne({
    where: { humanId: record.id, filename: data.filename },
    paranoid: false,
  });

if (file) {
    const prefix = Date.now().toString();
    // eslint-disable-next-line no-undef
    const fileParts = data.filename.split('.');
    filename = `${fileParts[0]}-${prefix}.${fileParts[1]}`;
  }

#序数后缀函数

function ordinal_suffix_of(i) {
    var j = i % 10,
        k = i % 100;
    if (j == 1 && k != 11) {
        return i + "st";
    }
    if (j == 2 && k != 12) {
        return i + "nd";
    }
    if (j == 3 && k != 13) {
        return i + "rd";
    }
    return i + "th";
}

【问题讨论】:

    标签: javascript node.js typescript mariadb sequelize.js


    【解决方案1】:

    像这样?

    const data = [{
      "filename": "path.ext"
    }, {
      "filename": "path.ext-1st"
    }, {
      "filename": "path.ext-2nd"
    }]
    
    const ordinal_suffix_of = i => { var j = i % 10, k = i % 100; if (j == 1 && k != 11) { return i + "st"; } if (j == 2 && k != 12) { return i + "nd"; } if (j == 3 && k != 13) { return i + "rd"; } return i + "th";};
    
    const incFile = filename => {
      const fileParts = filename.split('.');
      const [suffix,ord] = fileParts[1].split("-");
      let num = ord ? parseInt(ord) : 0;
      fileParts[1] = suffix + "-" + ordinal_suffix_of(++num);
      return `${fileParts[0]}.${fileParts[1]}`
    };
    
    const newFiles = data.map(({filename}) => incFile(filename))
    console.log(newFiles);

    【讨论】:

    • 应该是 path-1st.ext
    • 它也应该以数据库中的记录为基础,例如如果我添加相同的文件名 3 次或多次?
    • 查看更新。将 .ext 更改为 .ext-1st,将 ext-1st 更改为 ext-2nd,依此类推
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多