Himmators Himmators - 5 months ago 63
Node.js Question

Check if record/model is Unique using sequelize.js

I have a userAttribute table with normalized data. I looks like this:

UserAttribute = sequelize.define('userAttributes', {
name: {
type: Sequelize.STRING,
allowNull: false
},
value: {
type: Sequelize.STRING,
allowNull: false
},
};

User.hasMany(userAttributes);
userAttributes.belongsTo(User);


Some of the data has to be unique. For example, if the name is email, the value cannot be used by another record with the name email, because every user has to have a unique email.

I know I could make a model-validation and look it up in the database, but this seems very inefficient. I could also put all data that has to be unique in their own columns in the User-model, but is there some good way to keep the data in the userAttributes-table? For example check that the entire model is unique.

Answer

There might be a solution to your question.

Any number of attributes

Unique constraints are enforced via the database model. Since the setup in your question has a user with an indefinite amount of parameters, the only option remaining is indeed checking for uniqueness manually.

A specific number of attributes

If you would like to save all attributes in the table userAttributes but know a definite number of attributes beforehand, there is another method for connecting the User to multiple unique userAttributes.

Specify a relation between the two models for each attribute, e. g.

UserAttribute = sequelize.define('userAttributes', {
    name: {
        type:       Sequelize.STRING,
        allowNull:  false
    },
    value: {
        type:       Sequelize.STRING,
        allowNull:  false
    }
};

User.hasOne(UserAttribute, {
    as : 'email'
});
User.hasOne(UserAttribute, {
    as : 'firstName'
});
User.hasOne(UserAttribute, {
    as : 'lastName'
});

Then you can create a user like so (update works equally well):

User.create({
    email : {
        name : 'email',
        value : 'test@example.com'
    },
    firstName : {
        name : 'firstName',
        value : 'John'
    },
    lastName : {
        name : 'lastName',
        value : 'Doe'
    }
});
Comments