问题
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.
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 that changes the filename (current implementation usi
if (file) {
//this is where we add number to filename
filename = getNumberedFileName(data.filename)
}
#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;
}
回答1:
#suggetion
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
来源:https://stackoverflow.com/questions/63206044/making-a-record-unique-by-incrementing-a-number-in-javascript