Sequelize: Change "validate" meta data of column - javascript

Is it possible to change the "validate" meta data of a column using a migration file? I tried the queryInterface.changeColumn method and it seems like it can only change the three meta data mentioned in the docs (defaultValue, allowNull, and type).
I've tried doing something like this inside the 'up' object of the migration file:
queryInterface.changeColumn(
'tableName',
'columnName',
{
validate: {
is: /new_regex_validation/
}
}
)
However, the above attempt did not work for me when I ran "sequelize db:migrate"
For simplicity's sake, I'll use a table definition to elaborate on my question:
I'm trying to change an already existing table like this:
var tableName = sequelize.define('tableName', {
columnName: {
type: DataTypes.STRING,
unique: true,
allowNull: false,
validate: {
is: /some_regex_validation/
}
}
})
into this using sequelize migration:
var tableName = sequelize.define('tableName', {
columnName: {
type: DataTypes.STRING,
unique: true,
allowNull: false,
validate: {
is: /a_new-or-different_regex_validation/
}
}
})
or simply remove the validate meta data while using sequelize migration:
var tableName = sequelize.define('tableName', {
columnName: {
type: DataTypes.STRING,
unique: true,
allowNull: false
}
})
Any ideas?

Validation happens on the client, not on the database. You don't need a migration for it.

I came across this question a few times trying to understand the difference between building my model with validations and using migrations.
I found this link very helpful. Hopefully someone else does in the future.
Difference between Validations and Constraints
Validations are checks performed in the Sequelize level, in pure
JavaScript. They can be arbitrarily complex if you provide a custom
validator function, or can be one of the built-in validators offered
by Sequelize. If a validation fails, no SQL query will be sent to the
database at all.
On the other hand, constraints are rules defined at SQL level. The
most basic example of constraint is an Unique Constraint. If a
constraint check fails, an error will be thrown by the database and
Sequelize will forward this error to JavaScript (in this example,
throwing a SequelizeUniqueConstraintError). Note that in this case,
the SQL query was performed, unlike the case for validations.
https://sequelize.org/master/manual/validations-and-constraints.html

Related

mongodb not detecting unique value in my node js project

I'm working on mongodb with node js and I realized that even though I used the unique true property on unique fields in my project, I realized that it doesn't work, what is the reason?
my code is like this
const CourseSchema = new Schema({
name: {
type: String,
required : true,
unique:true
},
description: {
type: String,
required: true,
trim: true,
},
createdAt: {
type: Date,
default: Date.now,
},
});
i want to prevent this code from saving duplicate usernames.
Such a check if not directly possible with the mongoDB library. However it is supported out of the box if you use mongoosejs
It may be possible that you already have duplicate values in your document before defining this property Delete the messed data from the MongoDB collections,
or make sure that mongodb auto indexing is true
mongoose.connect('url', {
useNewUrlParser: true,
useCreateIndex: true,
autoIndex: true,
})
I tried many ways, but I realized that this problem is version-related.
I found the solution by updating the version, thank you for your solution support.

is there a way to create Keystone lists in runtime after keystone initialisation?

I'd like to create a KeystoneJs (v5.0.6) during runtime as some lists might be dynamically generated by the user.
If I run the following command after keystone has been intialised, I get the error: "Error: keystone.createList must be called before keystone.prepare()"
keystone.createList("MyDynamicList", {
fields: {
name: { type: Text },
email: {
type: Text,
isUnique: true,
},
},
});
Is there a way lists can be generated dynamically during runtime?
this is not possible, all the lists (and fields) has to be provided in keystone.createList method. keystone generates all the schema for GraphQL before you run keystone.connect.
There was a PR and request for delaying initialization in case someone wanted to add a field using a plugin before keystone.connect call which was denied.
Based on that discussion it is highly unlikely that this type of request even be priority for long.

How to make strict associations in Sails.js

Here are my two models that were generated using sails generate api model_name
Guitar.js
module.exports = {
schema: true,
attributes: {
brand:{
type: 'string',
required: true
},
messages:{
collection: 'message',
via: 'guitar'
}
}
};
Message.js
module.exports = {
schema: true,
attributes: {
text:{
type: 'string',
required: true
},
author:{
type: 'string',
defaultsTo: 'Anonymous author'
},
guitar:{
model: 'guitar',
required: true
}
}
};
Basically, a guitar can have many messages.
The problem comes when I insert new messages into the DB:
POST http://localhost:1337/message/
With JSON content:
{
"text": 4,
"author": "33434",
"guitar": null,
"extra": "This attribute will be removed because schema: true"
}
If I send this, the server will throw an error because the message must have a guitar.
However, if I instead write "guitar": 34, and 34 is a guitar ID that doesn't exist, the message will be added, and guitar will be changed to null. Weird.
This seems to be a bug, or maybe it's the intended behaviour but with a NoSQL database in mind.
I need to make strict associations so that all data makes sense. I hope I don't have to create my own controller manually that handles this logic the way I want.
Basically what I want is that Sails throws an error when the ID of the association doesn't exist.
By the time I write this, I came up with a solution: Just configure this on the DB server (MySQL, etc) so that the foreign key must exist and then handle the error in Sails. But I'm not very happy with it since it depends on the DB server. I'd like this to work even with localDiskDb.
My other solution would be to actually write manually a controller and see what happens by using something like Guitar.find(id).add(new_message) (maybe it's wrong, I haven't tested this)
I am not sure about this but have you tried like this :
http://localhost:1337/message/create?text=4&author=3343&guitar=somerandomString

Create multiple user contracts in Meteor

I want to create a system where multiple contracts can be created belonging to different users.
In Django, Ruby, etc., I would create a model Contract with field user = models.ForeignKey(settings.AUTH_USER_MODEL) but I don't know how to do this in Meteor.
Is it better to make a schema with
Schema.User = new SimpleSchema({
contracts: {
type: [Object],
},
"contracts.$.start_date": {
type: Date,
},
"contracts.$.end_date": {
type: Date,
},
"contracts.$.salary": {
type: Number,
}
});
or something like that? And then use meteor-autoform to create these? It seems very difficult to make objects relational in Meteor.
MongoDB isn't a relational database and so you'll need to manually handle relationships yourself (using multiple queries). Traditionally a Mongo document would use embedding whenever possible and use separate collections when necessary. See here for more information:
MongoDB relationships: embed or reference?
However, Meteor throws a spanner in the works since the publish model can only publish top-level documents, and there's little support for document hierarchies when writing templates etc.
Therefore the normal approach under Meteor is to create table for each collection and to have a records refer to other records using an ID:
Schema.User = new SimpleSchema({
contracts: {
type: [String],
},
...
});
Schema.Contract = new SimpleSchema({
user: {
type: String,
index: true
},
...
});
Although this will result in you having to do multiple queries, the structure will work very will with Meteor's design philosophies.

Are there any Mongoose validation libraries?

I am new to mongoDB and mongoose in fact I am new to Javascript as a whole. As a result of this I'm not sure of how I should go about sanitizing my data.
I was wondering if there are any libraries with custom validation functions that take care of at least some generic dangers one should watch out for. Also it would be nice if it already had commonly used validation such as email, or character length.
Hi there are many libraries for mongoose schema validation.some of are listed below.
https://github.com/leepowellcouk/mongoose-validator,
https://github.com/SamVerschueren/node-mongoose-validator
both are good library for mongoose validation..Also mongoose provide custom logic for validation.
More if you want to create custom logic then https://github.com/chriso/validator.js helpful to you.
for email validation i use this
const emailRegex = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/
email: {
type: String,
trim: true,
unique: true,
required: 'Email address is required',
validate: {
validator: (email)=> {
return emailRegex.test(email)
},
message: '{VALUE} is not a valid email'
},
match: [emailRegex, 'Please fill a valid email address']
}

Categories