Motocarota Motocarota - 2 months ago 16x
Javascript Question

How to generate a unique invoice id in Sails.js

I need to make Sails generate an unique ID for my invoices with the current format:



the idea was to follow the example in the documentation

function getLatestId() {
//stuck here
return 42;

const current_year = new Date().getFullYear()
const calculated_id = getLatestId() +"/"+ current_year

Invoice.create({ data:'...', id: calculated_id }).exec(function (err, item){
if (err) { return res.serverError(err); }

sails.log('Invoice created:',;
return res.ok();

The problem is that even with a working
function the code is ugly and it code smells from a mile.

Even trying to update the id in the exec callback of the create function looks odd, because an item with a specific id is already created.

I cannot believe that sails doesn't have something to address a similar scenario, but I can't find anything in the docs either.


1.You need to check if this generated ID exist

2.To generate uID under node use crypto

const crypto = require('crypto');
const uID = crypto.randomBytes(2).toString('hex');


'use strict';
const crypto = require('crypto');

function generateID(callback) {
  let uID = crypto.randomBytes(2).toString('hex'); //eg.uID = 3d4f
  let current_year = new Date().getFullYear();
  let uID = uID +"/"+ current_year;

  Invoice.findOne({id: uID}).exec(function(err, invoice) {
    if(err) {
      //catch Error
    } else {
      if(invoice) {
        // nope... uID exist
        return generateID(callback);
      } else {
        return callback(uID)

generateID(function (uID) {
  Invoice.create({ data:'...', id: uID }).exec(function (err, item) {
    if (err) {
      // return res.serverError(err);  <-- It's bad idea sending whole err to client. It's may expose your app architecture
      return res.serverError({errCode: 001, message: '<Your custom message>'});
    } else {
      sails.log('Invoice created:',;
      // return res.ok(); <-- It's OK, but if u use new version of sailsJS you should have created response (201). You can see code in responses/created.js
      return res.created();


Here is few another methods to generate random: