Skip to content Skip to sidebar Skip to footer

Unique Primary Key For ES6 Node.js/Express.js Model Object

In a Node.js/Express.js app, what specific changes need to be made to the ES6 AppUser model object below so that the name primary key will always be unique? As context, the user i

Solution 1:

I propose to figure out the problem with vanillia. If you just want to check if name is unique during execution of the app, you could store names used for instanciation of the class in an array

'use strict';
var store = []
class AppUser {
  constructor(name) {
    if (store.indexOf(name) === -1) {
      this.name = name;
      store.push(name)
    }
    else {
      console.log("warning " + name + " already exists");
      return;
    }
  }
  getName() {
    return this.name;
  }
}

var user1 = new AppUser("marco");
var user2 = new AppUser("raphaello");
var user3 = new AppUser("marco");
console.log(user2.getName());

run :
warning marco already exists
raphaello

Of course it's just an idea, and if this idea would deserve to be remained, throwing an exception would be better to make the instanciation abort than my return


Post a Comment for "Unique Primary Key For ES6 Node.js/Express.js Model Object"