title: Sort descending String with Number in Mongo DB
body: <p>I have currently a DB with two fields. Only one of them matter for the purpose of this question.</p>
  
  <p>Imagine a DB with a single String field (let's call it "Tags"), and the following pattern: <code>[a-z]*[0-9]*</code>, like:</p>
  
  <ul>
  <li>test129</li>
  <li>test130</li>
  <li>some43</li>
  <li>some44</li>
  <li>some45</li>
  <li>...</li>
  </ul>
  
  <p>My application needs to generate new "Tags", given the prepend "identifier" (like <code>test</code> or <code>some</code>).</p>
  
  <p>So let's say I input <code>test</code> as the prepend name, and <code>100</code> as the number of "Tags" to generate. </p>
  
  <ul>
  <li>He finds the LAST tag with the prepended name <code>test</code> on it.</li>
  <li>Parses the number after the prepended name.</li>
  <li>Sum +1 on that number, and generate 100 tags with the sequence.</li>
  </ul>
  
  <p>Output in this specific case, would be: <code>test131</code>, <code>test132</code>, ..., <code>test230</code>.</p>
  
  <p>I implemented this, and it was working just great with <code>Mongoose</code>. However, when I tried to generate a "Tag" from a already existent Tag with more than 1000, I found that the first step was a flaw. It was returning, let's say <code>test999</code> instead of <code>test1200</code>, and causing the iteration to start from 999, and getting errors since it needs to be unique.</p>
  
  <p>This is because, sorting a String differs from sorting a Number. I know the problem, but how can I solve this in a simple way, without having to create extra fields?</p>
  
  <p><strong>UPDATE</strong>: Part of the code where I find the tag:</p>
  
  <pre><code>   lastAliasNumber: function (next){
          console.log('process.lastAliasNumber');
  
          // Skip if prefix is not set (tags already have name)
          if(!prefix) return next();
  
          // Build RegExp to find tags with the prefix given
          var regexp = new RegExp('^'+prefix+'[0-9]+$', 'i');
  
          Models.Tag
              .findOne()
              .where({
                  alias: regexp
              })
              .sort('-alias')
              .exec(function (err, tag){
                  if(err) return next(err);
  
                  // Remove prefix and try parsing number
                  var lastId = 100;
  
                  if(tag){
                      // Remove prefix
                      var number = tag.alias.toLowerCase().replace(prefix, '');
  
                      // Get number from it
                      number = parseInt(number);
                      if(number) lastId = number;
                  }
                  console.log('lastAliasNumber', lastId);
                  next(null, lastId);
              });
      },
  </code></pre>