How do I set up sequelizejs to use a version column? - postgresql

How do I set up Sequelize to use an auto increment version number?
According to the documentation, all I need is just setting version: true: http://docs.sequelizejs.com/manual/tutorial/models-definition.html#configuration
First attempt:
import Sequelize from "sequelize";
export const sequelize = new Sequelize('my_connection', 'fake-user-name', 'fake-password', {
host: 'localhost',
dialect: 'postgres'
});
export const User = sequelize.define('user', {
id: {type: Sequelize.STRING, primaryKey: true},
name: {type: Sequelize.STRING, allowNull: false}
}, {
underscored: true,
tableName: 'r_users',
version: true // <- here
});
Result: there is no version column created.
Second attempt:
import Sequelize from "sequelize";
export const sequelize = new Sequelize('my_connection', 'fake-user-name', 'fake-password', {
host: 'localhost',
dialect: 'postgres'
});
export const User = sequelize.define('user', {
id: {type: Sequelize.STRING, primaryKey: true},
name: {type: Sequelize.STRING, allowNull: false},
version: { // <- here as well
type: Sequelize.INTEGER,
allowNull: false,
defaultValue: 0
}
}, {
underscored: true,
tableName: 'r_users',
version: true
});
Result: version column is created, but it doesn't auto increment when updating the record (I expect the below would increment version):
User.find({where: {id: 1}}).then(item => {
item.name = "Bob";
item.save();
});
Notes:
I'm using postgres 9.6 and the libraries I'm using are as below:
"sequelize": "^3.30.4"
"pg": "^6.2.3",
"pg-hstore": "^2.3.2",
Question:
Could anyone help me to point out what I have done wrong?
Thanks in advance.

Related

Property won't insert properly in Sequelize Model Create

I want to insert username, password, and role. But when I executed my function, the role property won't be executed.
This is my migration file:
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
username: {
type: Sequelize.STRING,
unique: true,
},
password: {
type: Sequelize.STRING,
allowNull: false,
},
role: {
type: Sequelize.STRING,
allowNull: false,
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
And this is my function for inserting new data (usermodel.js)
static register = ({ username, password }) => {
const encryptedPassword = this.encrypt(password);
return this.create({ username, password: encryptedPassword, role: 'user' })
}
This is what I got when I executed the function:
Executing (default): INSERT INTO "UserModel" ("id","username","password","createdAt","updatedAt") VALUES (DEFAULT,$1,$2,$3,$4) RETURNING "id","username","password","createdAt","updatedAt";
Is there anything that I do wrong? Any help will be appreciated, thanks!
Apparently, the problem is within the model. I haven't defined the role in the model init. I solved it by adding the role in model:
UserModel.init({
username: DataTypes.STRING,
password: DataTypes.STRING,
role: DataTypes.STRING
}

Mongo does not want to delete

I use remove and deleteMany and deleteOne, with curly brackets, and without but query always shows that they were not deleted, just always.
Author.deleteMany({}) Book.deleteMany({})
Even deleteOne ({}) does not work!
const mongoose = require('mongoose')
const schema = new mongoose.Schema({
name: {
type: String,
required: true,
unique: true,
minlength: 4
},
born: {
type: Number,
},
})
module.exports = mongoose.model('Author', schema)
const schema = new mongoose.Schema({
title: {
type: String,
required: true,
unique: true,
minlength: 2
},
published: {
type: Number,
},
author: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Author'
},
genres: [
{ type: String}
]
})
module.exports = mongoose.model ('Book', schema)
I should have used .then or await. Only they get all documents deleted
const results = await this.Book.deleteMany({});

Sequelize model case insensitive

I am using sequelize to make query in Redshift.
However Redshift is case-insensitive for Table Column Names, so all table names are lowercase.
And sequelize model isnt case-insensitive. So when I do a query findById, it execute this query:
SELECT "id", "userId", "summonerId", "name", "profileIconId", "summonerLevel", "revisionDate", "createdAt", "updatedAt" FROM "Lol" AS "Lol" WHERE "Lol"."id" = '463d118c-2139-4679-8cdb-d07249bd7777222';
It works if I execute the query inside Redshift, but sequelize just bring me back id and name column names, because only that have the name lowercase in model.
So how I can make sequelize case-insensitive? I tried the field option, but doesnt work.
So my model is:
lol = sequelize.define('Lol', {
id: {
type: Sequelize.STRING,
allowNull: false,
unique: true,
primaryKey: true,
field: 'id'
},
userId: {
type: Sequelize.STRING,
allowNull: false,
field: 'userid'
},
summonerId: {
type: Sequelize.INTEGER,
allowNull: false,
field: 'summonerid'
},
name: {
type: Sequelize.STRING,
allowNull: false,
field: 'name'
},
profileIconId: {
type: Sequelize.INTEGER,
allowNull: false,
field: 'profileiconid'
},
summonerLevel: {
type: Sequelize.INTEGER,
allowNull: false,
field: 'summonerlevel'
},
revisionDate: {
type: Sequelize.BIGINT,
allowNull: false,
field: 'revisiondate'
},
createdAt: {
type: Sequelize.DATE,
allowNull: false,
field: 'createdat'
},
updatedAt: {
type: Sequelize.DATE,
allowNull: false,
field: 'updatedat'
}
}, {
freezeTableName: true,
tableName: 'Lol'
})
Found a way.
Here is now my full setting to make Redshift work with Sequelize:
var Sequelize = require('sequelize');
Sequelize.HSTORE.types.postgres.oids.push('dummy'); // avoid auto-detection and typarray/pg_type error
AWS.config.update({accessKeyId: 'accessKeyId', secretAccessKey: 'secretAccessKey', region: "xxxxxx"});
var sequelize = new Sequelize('database', 'username', 'password', {
host: 'hostname',
dialect: 'postgres',
port: '5439',
pool: {
max: 10,
min: 0,
idle: 20000
},
returning: false, // cause sql error
quoteIdentifiers: false, // set case-insensitive
keepDefaultTimezone: true, // avoid SET TIMEZONE
databaseVersion: '8.0.2' // avoid SHOW SERVER_VERSION
});

Define array of objects based on a mongoose schema

I have the following schema in mongoose that I would like to have as a nested array in another schema:
var NestedSchema = new Schema({
name: { type: String, required: true }
});
Some other schema that needs and array of the nested schema.
var EventSchema = new Schema({
name: { type: String, required: true, unique: true },
fields: [NestedSchema]
});
Which works just fine. However now I want to run some validation against that array.
var validators = // some validators
var EventSchema = new Schema({
name: { type: String, required: true, unique: true },
fields: [{ type: 'NestedSchema', required: true, validate: validators }]
});
Of course type: 'NestedSchema' does not work, it was a shoot in the dark. Does mongoose allow you to have an array of object based on schema
Using:
MongoDB shell version: 3.2.12,
Mongoose : 4.4.7
I managed to have an array based on schema that way:
var NestedSchema = new Schema({
name: { type: String, required: true }
});
var EventSchema = new Schema({
name: { type: String, required: true, unique: true },
fields: [{ type: [NestedSchema], required: true }]
});
Did not try validation, but I believe it will work as required works well. :)

Sails js and Sequelize, no associations added to database

This is how my models are structured in sails:
myapp
--api
----controllers
----models
-----User.js
------Role.js
User.js
module.exports = {
attributes:{
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
username: {
type: Sequelize.STRING,
},
password: {
type: Sequelize.STRING,
}
},
associations: function() {
User.hasOne(Role, {foreignKey: 'id', as: 'role' });
}
};
Role.js
module.exports = {
attributes:{
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
name: {
type: Sequelize.STRING,
}
}
};
After sails lift, in the postgresql I have users table with id, username, password, createdat and updatedat + roles table with id, name, createdat and updatedat. No foreignKey for Roles in Users table.
How I can fix this?
I'm using sails-hook-sequelize and sails-hook-sequelize-blueprints, can this occur because of them?
Thanks!
Edit:
The correct way was:
module.exports = {
attributes:{
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
username: {
type: Sequelize.STRING,
},
password: {
type: Sequelize.STRING,
}
},
associations: function() {
User.hasOne(Role, {
as : 'role',
foreignKey: {
name: 'roleId',
allowNull: false
}
});
}
};
The createdAt and updatedAt columns are added by default unless you set the timestamps option to false. See the docs.
To add foreign key constraints, you need to define associations for the Roles model.