通过增加 javascript 中的数字使记录唯一 [英] making a record unique by incrementing a number in javascript
问题描述
如果文件名已存在于数据库中(也基于记录),我想为文件名增加一个数字.例如,如果我添加文件名为 DOC 的文件,它将检查 DOC 是否存在,因为下面的示例中存在 DOC 并且最新的增量为 1 (DOC-1),则文件名将是 DOC-2.如果我再次添加 DOC 并且最新的增量为 2,那么新文件名将是 DOC-3.so,依此类推.有什么想法吗?谢谢.
I wanted to increment a number to a filename if the filename already exists in the database (based on the records too). for example if I add file with filename DOC it will check if DOC exist since DOC exist on the example below and the latest increment is 1 (DOC-1) then the filename would be DOC-2. If I add DOC again and the latest increment is 2 so the new filename would be DOC-3.so on and so forth. Any idea guys ? thank you.
听起来我想要的是始终创建一个新的文件名(通过向文件名添加一个增量或数字),也可能在 .future 中找到作为相同数据更新的多个文件名.
Sounds like what I want is to always create a new filename (by adding an increment or number to a filename) , also to potentially in .future locate multiple filenames that are updates of the same data.
#用于搜索记录是否存在的代码(工作正常)
#Code for searching if record exists(works fine)
const file = await context.service.Model.findOne({
where: { employeeId: record.id, filename: data.filename },
paranoid: false,
});
#code 更改文件名(当前实现 usi
#code that changes the filename (current implementation usi
if (file) {
//this is where we add number to filename
filename = getNumberedFileName(data.filename)
}
#code 为文件名添加数字
#code to add number to filename
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;
}
推荐答案
#suggetion
您的逻辑可能会破坏 ACID 规则我认为您可以尝试添加一个 numberOfFiles 列,并使用更新 sql 查询,例如update set numberOfFiles = numberOfFiles + 1 where yourTable
Your logic could break ACID rules in my view you could try adding an numberOfFiles column instead and use update sql query like
update set numberOfFiles = numberOfFiles + 1 where yourTable
这篇关于通过增加 javascript 中的数字使记录唯一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!