javascript - 通过增加 javascript 中的数字使记录唯一

标签 javascript mysql node.js typescript sequelize.js

如果文件名已存在于数据库中(也基于记录),我想将一个数字增加到文件名。例如,如果我添加文件名为 DOC 的文件,它将检查 DOC 是否存在,因为下面的示例中存在 DOC,并且最新的增量为 1 (DOC-1),则文件名将是 DOC-2。如果我再次添加 DOC 并且最新的增量为 2,那么新文件名将是 DOC-3.so,依此类推。有什么想法吗?谢谢你。
听起来我想要的是始终创建一个新文件名(通过向文件名添加增量或数字),也可能在 .future 中找到作为相同数据更新的多个文件名。
#用于搜索记录是否存在的代码(工作正常)

const file = await context.service.Model.findOne({
    where: { employeeId: record.id, filename: data.filename },
    paranoid: false,
  });
# 更改文件名的代码(当前实现 usi
     if (file) {
//this is where we add number to filename
        filename = getNumberedFileName(data.filename)
      }
#code 将数字添加到文件名
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;
}
DATABASE RECORD

最佳答案

#建议
在我看来,您的逻辑可能会破坏 ACID 规则,您可以尝试添加 numberOfFiles 列,并使用更新 sql 查询,例如update set numberOfFiles = numberOfFiles + 1 where yourTable

关于javascript - 通过增加 javascript 中的数字使记录唯一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63206044/

相关文章:

php - cakePHP 使用 find() 方法进行查询

javascript - 调试 "Maximum call stack size exceeded"

javascript - 通过 jquery 连续描述 mousemove 事件

javascript - 当涉及AJAX时,如何在加载页面的特定部分时运行JavaScript?

javascript - 在JavaScript中比较音源和麦克风之间的声音

node.js - Sequelize : how to import definitions from an existing database

javascript - 从react-native获取文件上传图像,与 `&lt;input type="file"onChange={this.fileChangedHandler}> `

javascript - 如何在选择后插入节点?

php - 如何为按名称上传文件制作区分大小写的代码

mysql - 显示 mysql myisam 锁