首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >通过在javascript中递增数字来使记录唯一

通过在javascript中递增数字来使记录唯一
EN

Stack Overflow用户
提问于 2020-08-01 22:02:08
回答 1查看 197关注 0票数 0

如果文件名在数据库中已经存在(也基于记录),我想将一个数字递增到文件名。例如,如果我添加文件名为DOC的文件,它将检查DOC是否存在,因为DOC存在于下面的示例中,并且最新增量为1 (DOC-1),则文件名为DOC-2。如果我再次添加DOC,并且最新的增量是2,那么新的文件名将是DOC-3,依此类推。伙计们,你们知道吗?谢谢。

听起来我想要的是总是创建一个新的文件名(通过向文件名添加一个增量或数字),还可能在.future中定位多个文件名,这些文件名是相同数据的更新。

#搜索记录是否存在的代码(工作正常)

代码语言:javascript
复制
const file = await context.service.Model.findOne({
    where: { employeeId: record.id, filename: data.filename },
    paranoid: false,
  });

#更改文件名的代码(当前实现使用

代码语言:javascript
复制
     if (file) {
//this is where we add number to filename
        filename = getNumberedFileName(data.filename)
      }

#向文件名添加数字的代码

代码语言:javascript
复制
function getNumberedFileName(fileN) {
    //These are value initializations to cope with the situation when the file does not have a .
    var fileName = fileN;
    var fileExtension = "";
    var lastDotIndex = fileN.lastIndexOf(".");
    if ((lastDotIndex > 0) && (lastDotIndex < fileN.length - 1)) { //We are not interested in file extensions for files without an extension hidden in UNIX systems, like .gitignore and we are not interested in file extensions if the file ends with a dot
        fileName = fileN.substring(0, lastDotIndex);
        fileExtension = "." + fileN.substring(lastDotIndex + 1);
    }
    var lastDashIndex = fileName.lastIndexOf("-");
    if ((lastDashIndex > 0) && (lastDashIndex < fileName.length - 1)) {
        var lastPart = fileName.substring(lastDashIndex + 1);
        if (!isNaN(lastPart)) {
            var index = parseInt(lastPart) + 1;
            return fileName.substring(0, lastDashIndex) + "-" + index + fileExtension;
        }
    }
    return fileName + "-1" + fileExtension;
}

EN

回答 1

Stack Overflow用户

发布于 2020-08-01 22:19:03

#建议

在我看来,您的逻辑可能会破坏ACID规则,您可以尝试添加numberOfFiles列,并使用像update set numberOfFiles = numberOfFiles + 1 where yourTable这样的update sql query

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63206044

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档