FAQ Database Discussion Community


Ordering results of eager-loaded models in Node Sequelize

node.js,postgresql,sequelize.js
I have a complex set of associated models. The models are associated using join tables, each with an attribute called 'order'. I need to be able to query the parent model 'Page' and include the associated models, and sort those associations by the field 'order'. The following is having no...

Sequelize belongsToMany relationship not working

sequelize.js
First, I am loading my models with a function: module.exports = function(config) { var db, files, modelPath, myDb, sequelize; sequelize = new Sequelize(config.database, config.username, config.password, { dialect: 'postgres', host: config.host, port: config.port, logging: false, define: { charset: 'utf8', collate: 'utf8_general_ci' } }); db = {}; modelPath = __dirname + "/models";...

Sequelize find by association through manually-defined join table

node.js,sequelize.js
I know that there is a simpler case described here: Unfortunately, my case is a bit more complex than that. I have a User model which belongsToMany Departments (which in turn belongsToMany Users), but does so through userDepartment, a manually defined join table. My goal is to get all the...

Polygon insertion issue (due to SRID) on Postgres

postgresql,geolocation,geospatial,postgis,sequelize.js
I'm having trouble inserting a polygon into my table structure. I'm relatively new to PostGIS, so I may be making a pretty amateur mistake on this. My table is setup as "Regions" and I'm adding a column for my geometry: "SELECT AddGeometryColumn(" + "'public', 'Regions', 'geom', 4326, 'POLYGON', 2" +...

Change database connection depending on route in express.js with sequelize

javascript,node.js,express,sequelize.js
Is it possible to change the database connection in sequelize depending on the route? For example, Users have access to 2 different installations in a website: - example.com/foo - example.com/bar Upon login users are redirected to example.com/foo To get all their tasks for the foo site, they need to visit...

Sequelize: update in bulk

mysql,node.js,sequelize.js
I'm using Node.js, MySQL and Sequelize. I'd like to insert some 10k rows into a table at once. The table has custom primaryKey field, that is being set manually. The data are downloaded from web and are overlapping. I'd like to have a version of bulkCreate that wouldn't fail if...

How to implemet a Many-to-Many relationship in Sequelizejs which also have relationship attributes?

node.js,sequelize.js
So there are a lot of answers that explain how you model a Many-to-Many relationship in sequelizejs using hasMany() etc. But none of them has explained how and where do you store attributes which are created due to such an association, for eg: A customer can belong to or have...

Sequelize.js belongsToMany instance method create not working?

javascript,postgresql,sequelize.js
My models: 'use strict'; module.exports = function(sequelize, DataTypes) { var Entity; return Entity = sequelize.define('Entity', { name: { type: DataTypes.STRING, allowNull: false } }, { classMethods: { associate: function(models) { return Entity.belongsToMany(models.User); } } }); }; and 'use strict'; module.exports = function(sequelize, DataTypes) { var User; return User = sequelize.define('User',...

Set column order in sequelize.js

mysql,node.js,sequelize.js
I would like to put user_id column before the timestamps, how can i tell this to sequelize.define? sequelize.define('UserPassport', { method: DataType.STRING, token: DataType.STRING, social_id: DataType.STRING }, { classMethods: { associate: function(models) { UserPassport.belongsTo(models.User); } }, tableName: 'user_passports', underscored: true }); schema of the table: CREATE TABLE `user_passports` ( `id` int(11)...

Sequelizejs error when authenticating with passportjs(facebook)

node.js,facebook,oauth,passport.js,sequelize.js
I am trying to authenticate with facebook OAuth thru passport.js but sequelizejs is throwing the following error: server-0 (err): Unhandled rejection SequelizeDatabaseError: column "value" does not exist My user model looks like this: module.exports = function(sequelize, DataTypes) { var User = sequelize.define("User", { username: { type: DataTypes.STRING, allowNull: true, validate:...

Extending an interface from a third party definition file

typescript,sequelize.js
I'm using this definition file in my Typescript code. The problem is that, according to Sequelize documentation to set the length of a string column, I should define its type as: Sequelize.STRING(20) and the current definition file doesn't allow this. It allows only Sequelize.STRING (which makes a default column length...

Node.js Arguments to path.join must be strings but arguments are a path

javascript,node.js,types,sequelize.js
I'm using the path module in Node.js version v0.10.36. It works on my laptop in Node.js version v0.10.30. I am basically passing a string contained in an object with one of the return values from a function handled by Sequelize that fetches from a MySQL Database. If I switch out...

Create row including association with hasOne in Sequelize

mysql,node.js,orm,sequelize.js
I'm testing different ORM's for Node.js and got stuck at this error: Possibly unhandled TypeError: undefined is not a function @ person.setUser(user); Tried person.setUsers, user.setPerson and user.setPeople. Also tried console.log to find the function with no luck. What am I doing wrong? var config = require('./config.json'); var Sequelize = require('sequelize');...

What does ^— With additional stack trace in a mocha test mean?

node.js,mocha,sequelize.js
I have a node.js project that is using mocha for it's testing. My most recent test that utilizes Sequelizes create() function for adding a row to a table now produces this message instead of the stack trace that I have always seen up until now... 1) Should be able to...

sequelize subquery as field

sequelize.js
I'm trying to get such query to be generated by sequlized: SELECT "Customers"."id", (SELECT SUM("Orders"."amount") FROM "Orders" WHERE "Orders"."CustomerId" = "Customers"."id") AS "totalAmount", "Customer"."lastName" AS "Customer.lastName", "Customer"."firstName" AS "Customer.firstName" FROM "Customers" AS "Customer"; I'm trying to avoid "GROUP BY" clause, as I have a lot of fields to select and...

how to remove association in sequelize without extra query?

mysql,node.js,orm,sequelize.js
I have many to many association between exercise and muscle models. I remove single association models.Exercise.find({where: {id: exerciseId}}) .then(function(exercise){ exercise.removeMuscle(muscleId); res.sendStatus(200); }); ORM runs 3 queries and 2 of them are similar Executing (default): SELECT `Muscule`.`id`, `Muscule`.`title`, `Muscule`.`description`, `Muscule`.`video`, `Muscule`.`createdAt`, `Muscule`.`updatedAt`, `muscle_exercise`.`createdAt` AS `muscle_exercise.createdAt`, `muscle_exercise`.`updatedAt` AS `muscle_...

sequelize belongsToMany giving TypeError: undefined is not a function

node.js,express,sequelize.js
I am using sequelize with express, I have defined my model like this "use strict"; var Sequelize = require('sequelize'); module.exports = function(sequelize, DataTypes) { var Order = sequelize.define("Order", { status: { type: Sequelize.INTEGER }, notes: { type: Sequelize.STRING } }, { classMethods: { associate: function(models) { Order.belongsTo(models.User); Order.belongsTo(models.Address); Order.belongsToMany(models.Items); }...

Sequelize Express multiple models

express,sequelize.js
I can't seem to figure out how to include multiple models. I have three models. Tabs, Servers, and Points Tabs hasMany Server Servers belongsTo Tabs and hasMany Points Points belongTo Server In my routes I am doing this: router.get('/', function (req, res, next) { models.TabConfig.findAll({ include: [models.ServerConfig] }).then(function (tabs) {...

SequelizeJS relations, same model

mysql,node.js,sequelize.js
I want to create a model that looks like this : var category = db.define('category', { name: { type: Types.STRING, }, position: { type: Types.INTEGER } }, { classMethods:{ associate: function (models) { category.belongsTo(models.category); category.hasMany(models.category); } } }); It works in my database, I have "CategoryId" in the category's table...

Create Association in Sequelize to do a Left Join

node.js,postgresql,sequelize.js
I want to do a left join using Sequelize that does the same as this SQL code. SELECT * FROM events LEFT JOIN zones ON event_tz=zid WHERE event_creator_fk=116; I have two tables: events and zones (with a list of time zones). When querying for all the events that are created...

Creating instance with an association in Sequelize

node.js,sequelize.js
Using Sequelize, I've created two models: User and Login. Users can have more than one Login, but a login must have exactly one user, which means a Login cannot be saved without a User ID. How do I .create a Login with a User association all in one swoop? Current...

How can I set up Sequelize.js to stream data instead of a promise / callback?

mysql,node.js,sequelize.js
I am using MySQL and have a very large response (15,000+ rows). This takes.. well.. time. But I can start to process the first result right away. Can I set up a stream somehow with sequelize? If so, how?

Sequelize: Querying if ARRAY contains a value

postgresql,sequelize.js
Suppose I have a PG ARRAY field: id | array | ===|=============| 1|{"1","2","3"}| How do I use sequelize to query to see if the array field as the value 1. I tried: array: { $contains: "1" } which gives me: array @> "1" with error: Possibly unhandled SequelizeDatabaseError: array value...

Sequelize where condition as raw

javascript,node.js,postgresql,sequelize.js
I have a model defined. I would like to do an advanced select query in postgres on that model. The raw query would look like this: SELECT 6371 * acos( cos( radians("+CustomerLat+") ) * cos(radians(sto.lat)) * cos( radians(sto.lng) - radians("+CustomerLng+") ) + sin( radians("+CustomerLat+") ) * sin(radians(sto.lat)) ) AS distance...

Node.js / Sequelize.js / Express.js - How to insert into many-to-many association? (sync/async?)

javascript,node.js,promise,sequelize.js
I have two models (Individual, Email) and am trying to insert into the created 'Individual_Email' table using the Sequelize commands. While Sequelize is creating the desired table, it returns the following error when trying to add/get/set to/from that table: "Object [object Promise] has no method 'addEmail'". What am I missing?...

How to use of AND and OR operator in same query in sequelize?

mysql,node.js,sequelize.js
I execute the below query but i gives error. I want the result of my SQL query which i posted at end. userServiceAppointmentModel.findAll({ where: { technician_id: resultsFromAuthentication.technician_id, is_confirmed_by_user: 1, $or: { service_start_time: { gte: curLocalDate }, service_running_status: 1 } }, attributes: attributes }).complete(function (err, appointmentResponse) { if (err) { console.log(err);...

Can't exclude association's fields from select statement in sequelize

javascript,node.js,sqlite,sequelize.js
I have the following code (simplified): var group = sequelize.define("group", { id: {type: DataTypes.INTEGER, autoIncrement: false, primaryKey: true}, name: type: DataTypes.STRING, parentId: DataTypes.INTEGER }, { classMethods: { associate: function (models) { group.belongsToMany(models.item, { as:'items', foreignKey: 'group_id', through: models.group_item_tie }); }} }); var group_item_tie = sequelize.define("group_item_tie", {}, {freezeTableName: true}); var item...

Sequelize error handling

javascript,node.js,sequelize.js
take a look at the example code below, I wonder if it is enough to just chain one .catch() on the outer most sequelize task instead of always chaining it on each task which looks quite messy. The second question would be is it possible to make .then(instance, error) contain...

How properly handle async functions in nodejs

javascript,node.js,sequelize.js
I am new to nodejs, and I don't properly understand how async functions works. I read about them a lot today, but I cant solve my problem. I use Sequelize.js as the ORM and my problem is when I nest a query into the callback of an other query then...

Returning a response immediately with res.json

javascript,node.js,express,sequelize.js
I have an express route which takes in some parameters, queries the database, and then returns some response. I am using sequelize to query the db: router.get('/query', function(req,res) { var name = req.params.name; var gid = req.params.gid; // Query the db models.user.find({ where: { name: name }}).then(function(user) { models.group.find({ where:...

Sequelize.js many to many eager loading

database,node.js,many-to-many,sequelize.js,eager-loading
I have 2 models: User and Team There are multiple kinds of users (in this case Mentors and Moderators) which are differentiated using an attribute in the User model(). The associations between User and Team are as below: User.hasMany(models.Team, {as: 'Mentors', through: models.TeamMentor, foreignKey: 'mentorId'}); User.hasMany(models.Team, {as: 'Moderators', through: models.TeamModerator,...

How do I create a required “BelongsTo” association using Sequelize?

node.js,sequelize.js
Using Sequelize, I've created two models: User and Login. Users can have more than one Login, but a login must have exactly one user. How do I specify in the login model that a user must exist before a save can occur? Current Code var User = sequelize.define('User', {}); var...

Sequelize.js - how to properly use get methods from associations (no sql query on each call)?

node.js,orm,sequelize.js
I'm using Sequelize.js for ORM and have a few associations (which actually doesn't matter now). My models get get and set methods from those associations. Like this (from docs): var User = sequelize.define('User', {/* ... */}) var Project = sequelize.define('Project', {/* ... */}) // One-way associations Project.hasOne(User) /* ... Furthermore,...

Alphanumeric ID in sequelize.js

node.js,postgresql,orm,sequelize.js,alphanumeric
I'm using sequelizejs with PostgreSQL as ORM in my webapp, I want to use alphanumeric ID instead numeric.How can I do that ? Is there some way to do it through sequelize? Or do I want to generate this id separately and then save it into db ? Thanks for...

How to add a case-insensitive unique constraint in a SequelizeJS Model when using Postgresql?

node.js,postgresql,sequelize.js
var Model = sequelize.define('Company', { name: { type: DataTypes.STRING, unique: true } } In the above example, unique: true is case sensitive. It allows both "sample" and "Sample" to be saved in the db. Is there a built-in way to do this in sequelize without having to write a custom...

What is the difference between .save and .create in Sequelizejs?

mysql,node.js,orm,sequelize.js
I'm new to Sequelize, and trying hard to understand how this very strange, new world of ORMs works. Once thing that I can't seem to understand is the difference between ".create" and ".save" in Sequelizejs. I have written test functions with both, and besides having slightly different syntax, they both...

Sequelize bulk update different behaviour

sequelize.js
I cannot find the problem in my sequelize model. When I bulk update (seed) my users I get a different pwd set and therefore cannot login. When I update the db entry to the correct pwd, it obviously works. There seems to be something wrong maybe with the bulk update...

Sequelize Query in Express-Module-Function

node.js,express,sequelize.js,synchronous
I'm using Sequelize with node.js and the express framework. I need to implement a function in my app-module which provides specific information from the database. My current approach is this: var app = express(); app.provide = function(){ models.Project.findAll({ include: [{ all: true}]}).then(function(data){ return data; }); }; module.exports = app; My...

Using sequelize.js to interface against existing database?

node.js,sequelize.js
I'm currently working in a project where our Node.js server will perform a lot of interactions against an existing MySQL database. Thus I'm wondering if Sequelize is a good library to interface the database. From what I've read about it, it is most often used as a master of the...

Sequelize - Inserting multiple associated entities in transaction fails

transactions,associations,sequelize.js
I have two models: Status and StatusParameter. Status 'hasMany()' StatusParameter and StatusParameter 'belongsTo()' Status. I want to insert a Status record and then insert multiple StatusParameter entities associated to the new Status. I want to wrap all the inserts in a transaction as well. I am using Sequelize 2.0.5, so...

Sequelize limit include association

javascript,mysql,sequelize.js
I have a problem with Sequelize when limiting results and including associated models. The following produces the correct result, limited by 10 and sorted correctly. Visit.findAll({ limit: 10, order: 'updatedAt DESC', }).success(function(visits) { res.jsonp(visits); }).failure(function(err) { res.jsonp(err); }) SQL SELECT * FROM `Visits` ORDER BY updatedAt DESC LIMIT 10; However...

Sequelize time comparison failed after database replacement to postgreSQL

javascript,node.js,postgresql,orm,sequelize.js
I've replaced MySQL database instead PostgreSQL and now I have issue when I'm trying find user through : .find({ where: { resetPasswordToken: req.params.token, resetPasswordExpires: { gt: Date.now() } } }) .then(function(user){ if (!user) { req.flash('errors', { msg: 'Password reset token is invalid or has expired.' }); return res.redirect('/forgot'); } res.render('account/reset',...

Does sequelize have any change tracking built-in mechanism?

javascript,node.js,sequelize.js
I was wondering whether sequelize implements (or plans to implement) any change tracking mechanism, which goal would be to avoid running unnecessary queries. For example: var user = sequelize.User.find { where: { name: 'bob' } }; user.name = 'john'; user.save(); The sequelize will of course update the username. Now, imagine...

How to use inner joins in sequilize

mysql,node.js,sequelize.js
SELECT v.vehicle_id,v.vehicle_model_id,u.user_id,u.first_name FROM user u INNER JOIN user_vehicle v ON u.user_id= v.user_id WHERE u.user_id=3 For the above query i use the following command userModel.find({ where: {user_id: 3}, include: [userVehicleModel] }).success(function(user){ console.log(user) }) It gives error:Possibly unhandled Error: user_vehicle is not associated to user! Thanks in advance....

Create n:m objects using json and sequelize?

javascript,json,node.js,sequelize.js
I am trying to learn sequelize, but am having trouble getting a n:m object created. So far I have my 2 models that create 3 tables (Store, Product, StoreProducts) and the models below: models/Store.js module.exports = (sequelize, DataTypes) => { return Store = sequelize.define('Store', { name: { type: DataTypes.STRING, },...

How to set nullable on association in Sequelize

sequelize.js
Lets say I have a League entity and a User entity and I want the manager (User) of that league to be mandatory. How can I tell Sequelize that there should be a not-null constraint on the League.ManagerId column? Here is how I defined my association: League.belongsTo User, {as: 'Manager'}...

Sequelize joining tables with multiple records with same foreign key

mysql,node.js,express,sequelize.js
I have sequelize database with 3 models. Team - primary key: id Participant - foreignKey refering to Team - teamId TeamResult- foreignKey refering to Team - teamId Each team can have multiple participants so there can be multiple records in participant table having same teamId. Same case with team results....

How can I drop all tables with Sequelize.js using postgresql?

postgresql,sequelize.js
I am trying: if (process.NODE_ENV === 'test') { foreignKeyChecks = 0; forceSync = true; } else { foreignKeyChecks = 1; forceSync = false; } global.db.sequelize.query("SET FOREIGN_KEY_CHECKS = " + foreignKeyChecks).then(function() { return global.db.sequelize.sync({ force: forceSync }); }).then(function() { return global.db.sequelize.query('SET FOREIGN_KEY_CHECKS = 1'); }).then(function() { var server; console.log('Initialzed database on:');...

Can't connect to MySQL with Sequelize

javascript,mysql,node.js,sequelize.js
I consistently get a SequelizeConnectionRefusedError when trying to connect to a MySQL database on my server. The login credentials are correct, the port is open, everything seems good (and works like a charm in the dev environment). Sorry for the scarce background information, but I'm dumbfounded here - I really...

Sequelize save in multiple tables

javascript,node.js,sequelize.js
Okay so i have a huge problem that i have no clue on how to fix. i have the following setup for my titles: var Title = sequelize.define('title', { id: DataTypes.INTEGER, name: DataTypes.STRING, organization_id: DataTypes.INTEGER }, { freezeTableName: true, instanceMethods: { retrieveAll: function (onSuccess, onError) { Title.findAll({order: 'Rand'}, {raw: true})...

How would you test this route code?

javascript,node.js,unit-testing,express,sequelize.js
I have the following route code. User is a sequelize model, jwt is for creating a JWT token. I want to avoid hitting the db, so I want to stub out both dependencies. User.create returns a Promise. I want to be able to assert that res.json is actually being called....

Writing Migrations with Foreign Keys with in SeqelizeJS

node.js,database-migration,sequelize.js
The Background I'm building a project with SequelizeJS, a popular ORM for NodeJS. When designing a schema, there appear to be two flavors of tactic: Create model code and use the .sync() function to automatically generate tables for your models. Create model code and write manual migrations using QueryInterface and...

How to create assocations in Sequelize migrations?

node.js,migration,sequelize.js
I am using migrations to create entities. Naturally, some have relations between them. Until now, by using sync(true), I enjoyed the benefit of Sequelize implementing the relations for me at the database level. How do I express new relations in a migration? One-to-many: Should I be taking care of the...

What is the use of contains and contained in sequelize Where clause?

mysql,node.js,sequelize.js
$contains: [1, 2] // @> [1, 2] (PG array contains operator) $contained: [1, 2] // <@ [1, 2] (PG array contained by operator) I want to know what is the actual use of both above opeartor...

Sequelize remove hook?

javascript,node.js,sequelize.js
I'm adding a hook to my model at runtime: model.addHook('afterUpdate', 'myHook', function(instance, cb) { // Do some stuff }) If some condition is met, I'd like to remove this hook so it no longer fires. Looking at the docs I can only see methods for adding / checking the existence...

Using group by and joins in sequelize

sql,node.js,postgresql,sequelize.js
I have two tables on a PostgreSQL database, contracts and payments. One contract has multiple payments done. I'm having the two following models: module.exports = function(sequelize, DataTypes) { var contracts = sequelize.define('contracts', { id: { type: DataTypes.INTEGER, autoIncrement: true } }, { createdAt: false, updatedAt: false, classMethods: { associate: function(models)...

Filter by belongsToMany relation field

sql,node.js,orm,sequelize.js
It is impossible to filter data using a linked table. There are two tables Instructor and Club. They related how belongsToMany. I need to get all Instructors which club_id = value. Instructor model: sequelize.define('Instructor', { instance_id: DataTypes.INTEGER, name: DataTypes.STRING(255) }, { tableName: 'instructors', timestamps: false, classMethods: { associate: function (models)...

Sequelize many-to-many self reference

postgresql,sequelize.js
I'm trying to get one of the association examples from sequelize working properly and it doesn't seem to be setting up the join table correctly. In the example we have one model called Person and then a many-to-many self-reference for a Person's children. Code: var Sequelize = require('sequelize'); var sequelize...

Sequelize saving many to many

node.js,postgresql,sequelize.js
I was wandering if there are any extended tutorials on how to save a many to many relationship? I find the documentation more than basic. Its missing many use case examples. I have two models: Client and Rule. They have the n:n relationship. Client: var Client = sequelize.define('client', { title:...

Sequelize query - compare dates in two columns

sequelize.js
I have a table in Sequelize with two date columns - i.e. with : var Visit = sequelize.define("Visit", { /*...*/ scheduleEndDate: { type: DataTypes.DATE } actualEndDate: { type: DataTypes.DATE } /*...*/ }); I want to make a query that returns rows where actualEndDate is before scheduleEndDate - and can't get...

Adding limit to sequelize findAll destroys the query?

node.js,postgresql,sequelize.js
I'm trying to return a group of Models, paginated using limit and offset, including the grouped count of that model's favorites. A fairly trivial thing to attempt. Here's my basic query setup with sequelize: var perPage = 12; var page = 1; return Model.findAll({ group: [ 'model.id', 'favorites.id' ], attributes:...

Nodejs Sequelize is not inserting

javascript,node.js,sequelize.js
OKay i have litteraly been staring at this for 2 hours now and i simply cannot find the mistake: I have the following database table: If you cannot tell it has 4 columns: id name organization_id competence_type_id Using sequelize i am using the following code: var Competence = sequelize.define('competence', {...

Prevent Sequelize from outputting SQL to the console on execution of query?

node.js,sequelize.js
I have a function to retrieve a user's profile. app.get('/api/user/profile', function (request, response) { // Create the default error container var error = new Error(); var User = db.User; User.find({ where: { emailAddress: request.user.username} }).then(function(user) { if(!user) { error.status = 500; error.message = "ERROR_INVALID_USER"; error.code = 301; return next(error); }...

How to validate array input for array field using Sequelize.js and PostgreSQL?

arrays,node.js,postgresql,validation,sequelize.js
I'm using Node.js + PostgreSQL + Sequelize.js 2.0.2. I have the following schema definition for the phone field which could be array of strings, but only number is allowed: var User = sequelize.define("User", { .... .... /** Phone number * Multiple numbers should be registered due to */ phone: {...

How to use of between operator in Sequelize?

node.js,sequelize.js
var conditionalData = { id: { $Between: [11, 15] }, technician_id: technicianId }; var attributes = ['id', 'service_start_time', 'service_end_time']; userServiceAppointmentModel.findAll({ where: conditionalData, attributes: attributes }).complete(function (err, serviceAppointmentResponse) { if (err) { var response = constants.responseErrors.FETCHING_DATA; return callback(err, null); } else { if (serviceAppointmentResponse.length > 0) { var response = constants.responseErrors.NO_AVAILABLE_SLOTS_IN_YOUR_CALENDAR;...

Sequelize is not loading the database tables properly

sequelize.js
I have an express server and it does: app.db = SequelizeData config.db app.db.sequelize.sync({force: false}).complete (err) -> console.log err console.log 'Initialzed database on:' console.log config.db SequelizeData is: (function() { 'use strict'; var Sequelize, fs, path, _; _ = require('lodash'); fs = require('fs-extra'); path = require('path'); Sequelize = require('sequelize'); module.exports = function(config)...

Custom .find() tied to a Sequelize Model

model,find,sequelize.js
Couldn't find what I wanted in the documentation, so I'm just going to leave this here and hope for some help! I have a specific query that I need to run on my user Model with a lot of includes and those includes all have where statements inside of them......

Getting parent category object with SequelizeJs

node.js,sequelize.js
I have a model defined as: var Post = sequelize.define("Post", { title: DataTypes.STRING, description: DataTypes.TEXT }, { classMethods: { associate: function (models) { Post.belongsTo(models.Category, {as: 'category', foreignKey:'categoryId'}); } } }); And then the category model as : var Category = sequelize.define("Category", { code: DataTypes.STRING, description: DataTypes.STRING, img: DataTypes.STRING, }, {...

sequelize with postgres database not working after migration from mysql

mysql,postgresql,sequelize.js,postgresql-9.3
I change MySQL databese into postgreSQL in sequelize. But After migration I have issue with upper and lowercase first letter in Table or Model... Before my MySQL version was working properly but after migration I got error message: 500 SequelizeDatabaseError: relation "Users" does not exist My User model: module.exports =...

NodeJS - Sequelize updating issue

mysql,node.js,sequelize.js
I have a problem with updating method. I am doing this: // Char is outside the object where update method is... Char = db.define('characters', {}, { tableName: 'characters', updatedAt: false, createdAt: false }); //... part of the whole object update: function ( columns, callback ) { Char.update( columns, { where:...

sequelize js with big integers

node.js,sequelize.js,bigint
I have an application written in Node JS and uses the Sequelize js ORM library to access my database which is MySql. My problem is that I have a column in my db which is BIGINT and when the value of it is large I get wrong values when I...

Unhandled rejection TypeError: Dependency name must be given as a not empty string

sequelize.js,hapijs
I got this error when codes hitting require('./models').sequelize.sync(). (models is a directory created by running command sequelize init) Could anyone give me some hints about what induces this error? > node src/server.js Unhandled rejection TypeError: Dependency name must be given as a not empty string at /Users/syg/Repos/example/node_modules/sequelize/node_modules/toposort-class/toposort.js:37:31 at Array.forEach (native)...

What do these hash/pound symbols in the Sequelize docs represent?

javascript,sequelize.js
My team is investigating javascript ORM frameworks for use in an upcoming project but I can't figure out what the heck these # symbols mean in the Sequelize docs but I know this is invalid JS. Here is an example taken from the docs here: // this will add the...

Setting up Models for the first time and for repeated use

sequelize.js
I'm going to be creating 5-7 models representing my tables. From what I'm reading, separate files for each Model is recommended and then I can import them into my main files. My question is in regards to sync() and the risks of running that multiple times. Looks like sync() should...

Sequelize, Raw Query by daterange

node.js,postgresql,sequelize.js
I use "sequelize": "^2.0.0-rc3" with pg (postgresql), in this moment i am trying to do a raw query with date range but sequelize don't return data. When I run the same query in postgresql db get correct results. Please Help Me. In sequilize: // Init main query var query =...

cast uuid to varchar in postgres when I use sequelize

postgresql,uuid,sequelize.js
I have a table with a column named _id of which the type is uuid. I cast the type of _id from uuid to varchar, in order to select the records as follows: SELECT "_id" FROM "records" WHERE "_id"::"varchar" LIKE '%1010%'; and it works well. _id -------------------------------------- 9a7a36d0-1010-11e5-a475-33082a4698d6 (1 row)...

Req.User values Default to 1st record in DB after Oauth Authentictation Redirect

node.js,redirect,express,passport.js,sequelize.js
after a successful authentication with Passport.js, I want a redirect to the user's profile page. However, after the redirect, the value of req.user is set to the first record of the database. So all users see user /1's profile page, instead of the intended page, let's say /33. How can...

Sequelize Associations not being created

mysql,node.js,sequelize.js
I am designing a system that has People and Users (all Users are people, but not all People are Users). Each of those entities can have multiple Emails. The Sequelize models are set up like this: Models Person module.exports = function(sequelize, Sequelize) { var Person = sequelize.define('person', { id: {...

sequelize association key is uppercased in response

sequelize.js
How can I make Music to be `music? { id: 4 name: "playlist 1" created_at: "2015-04-21T21:43:07.000Z" updated_at: "2015-04-23T20:44:50.000Z" Music: [ { id: 12 name: "Deorro - Five Hours (Static Video) [LE7ELS]" video_id: "K_yBUfMGvzc" thumbnail: "https://i.ytimg.com/vi/K_yBUfMGvzc/default.jpg" created_at: "2015-04-22T21:46:21.000Z" updated_at: "2015-04-22T21:46:21.000Z" playlist_id: 4 } ] } My query looks something like: .get(function...

sequelize gives the wrong table name

mysql,node.js,rest,express,sequelize.js
I have a database. Where i have a "user" table I am trying to create my first REST api using sequelize however when it executes my query i get the following in the console: SELECT `id`, `username`, `password`, `name`, `organization_id`, `type_id`, `join_date` FROM `users` AS `user` WHERE `user`.`id` = '1';...

How to add context to a Sequelize hook?

sequelize.js
I want to use a hook to perform access control on a row so that users can only access rows they own. The hook would add an additional where clause to ensure that the user is the owner of the row (ex: WHERE ownerId=user.id). The problem is, how do I...

How to update with Sequelize with 'NOW()' on a timestamp?

node.js,datetime,sql-update,sequelize.js
I'm trying to do something like the following: model.updateAttributes({syncedAt: 'NOW()'}); Obviously, that doesn't work because it just gets passed as a string. I want to avoid passing a node constructed timestamp, because later I compare it to another 'ON UPDATE CURRENT_TIMESTAMP' field and the database and source could be running...

Is this the proper way to use promises with Sequelize.js?

javascript,promise,sequelize.js
var newUser; newUser = { name: req.body.name, email: req.body.email, username: req.body.username, password: req.body.password }; global.db.User.create(newUser).then(function(dbUser) { var newEntity; newEntity = { name: newUser.name + " Default Entity" }; return global.db.Entity.create(newEntity); }).then(function(dbEntity) { console.log(dbEntity); return res.json(dbUser.display()); })["catch"](function(err) { console.log(err); return next(err); }); global.db is a Sequelize object that has a User...