1

As you can see below , I have a query that checks if the filename already exist and just add a timestamp to make it unique , now the timestamp is too long , I supposed wanted to use ordinal suffix instead of timestamp. How do we add an oridinal suffix everytime an existing file is found ?

Something like hellofilename-1st , hellofileaname-2nd. etc

Btw filename is the column in the database.

#CODE

// check if filename already exists
  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]}`;
  }

#code 2

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";
}

1 Answers1

0

You need to try to count all documents using regexp, and then if count !== 0, add the document with name

`hellofilename-${ordinal_suffix_of(count)}`

I'm not sure which db you are using, if it is MongoDB, then you can use $regex in query: https://docs.mongodb.com/manual/reference/operator/query/regex/

and method count: https://docs.mongodb.com/manual/reference/method/db.collection.count/

Maxim
  • 475
  • 1
  • 5
  • 15
  • I have using mariadb and sequelize –  Jul 31 '20 at 09:57
  • do i need all the count of the documents or just the count of documents with the same filename ? @maxim –  Jul 31 '20 at 09:58
  • Cause I only need to add ordinal suffix to a new file if that filename has the same filename on the databse –  Jul 31 '20 at 09:59
  • @Mr.MarkTawin Only docs with the same filename) About DB, for SQL there is keywords LIKE (for query) and COUNT and for sequelize should be similar methods – Maxim Jul 31 '20 at 12:18
  • @Mr.MarkTawin Hi, if the answer have helped you, you can mark it as Accepted) – Maxim Aug 06 '20 at 17:33