How to associate tables via id - database

How can I associate two tables in Sequelize? I tried belongsTo, but this doesn't work. Example:
First table:
users = sequelize.define('users', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
name: Sequelize.TEXT,
type: Sequelize.INTEGER
Second table:
profiles = sequelize.define('profiles', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
place: Sequelize.TEXT,
phone: Sequelize.INTEGER
Association:
profiles.belongsTo(users, {foreignKey: 'id'});
Request:
users.findOne({
where: {name: 'John'},
include: [{model: db.tables.profiles}]
}).then(function(user_data) {
console.log(user_data);
})
Returned [Error: profiles is not associated to users!]
I need to return the matched line of "users" and the line with the same id from the table 'profiles'. Where is the mistake?

You need to declare the association for both tables. From your schema I can't tell what the join condition is. If your profiles table also has a column user_id such that profiles.user_id = users.id, then you could say the following:
users.hasMany(profiles, {
foreignKey: 'id'
});
profiles.belongsTo(users, {
foreignKey: 'user_id'
});

Related

How can I query find() with an array of IDs variable in mongoose?

I have an array p_id which holds ObjectId of a Schema named "Panel". Now I want to find candidates from "Candidate" schema which have parentPanel same as id's present in p_id array.
This is the candidateSchema:
var candidateSchema = new Schema ({
name: {
type: String,
required: true,
},
votedBy: [{
type: Schema.Types.ObjectId,
ref: 'User',
default: null,
}],
parentPanel: {
type: Schema.Types.ObjectId,
ref: 'Panel'
}
});
I tried something like this;
Candidate.find({parentPanel: {$in: [p_id]})
.then(candidates => {
res.send(candidates)
})
.catch(err=>console.log(err));
This is the error I'm getting:
message: 'Cast to ObjectId failed for value "[
5d8734d2bf53280d76a3915a, ' +
'5d8734d2bf53280d76a3915e ]" at path "parentPanel" for model ' +
'"Candidate"', name: 'CastError', stringValue: '"[ 5d8734d2bf53280d76a3915a, 5d8734d2bf53280d76a3915e ]"', kind:
'ObjectId', value: [ 5d8734d2bf53280d76a3915a,
5d8734d2bf53280d76a3915e ], path: 'parentPanel', reason:
undefined, model: Model { Candidate }

Referencing a composite primary key in a Sequelize.js seed model

Is it possible to reference composite primary keys in Sequelize?
I'm working on a web-app that helps organize kitchen waste. The restaurant organizes its weeks and months into 'periods' where the first week of September would be '9.1'. For every period, I need to create a new batch of ingredient objects that can keep track of what their prices and quantities were for that period. I figure it would be best to make the period primary keys their combined month and week, as that will be unique in the database.
I may add year on later, but that doesn't change my problem.
The database I'm working with is Postgres.
This is my period table model in my sequelize seed file:
.then(() => queryInterface.createTable('periods', {
month: {
type: Sequelize.INTEGER,
validate: {
max: 12,
min: 1
},
unique: "monthWeekConstraint",
primaryKey: true
},
week: {
type: Sequelize.INTEGER,
validate: {
max: 4,
min: 1
},
unique: "monthWeekConstraint",
primaryKey: true
},
createdAt: {
type: Sequelize.DATE
},
updtedAt: {
type: Sequelize.DATE
}
}))
I'd like to reference the periods stored in the above table in my periodItems table, which I have (incorrectly) looking like:
.then(() => queryInterface.createTable('periodItems', {
periodMonth: {
type: Sequelize.INTEGER,
references: {model: 'periods', key: 'monthWeekConstraint'}
},
periodWeek: {
type: Sequelize.INTEGER,
references: {model: 'periods', key: 'monthWeekConstraint'}
},
day: {
type: Sequelize.INTEGER,
validate: {
min: 1,
max: 7
}
},
...other irrelevant fields...
}))
I'm definitely new to databases, so I apologize if I'm way off. I've gotten a few other tables doing what I'd like, but I've been stuck on this problem for a few days.
While it is possible to create composite primary keys in Sequelize by specifying primaryKey: true against more than one column (as you have already done above), Sequelize doesn't currently support composite foreign keys, so there is no way to reference a model/table which has composite primary keys.
See https://github.com/sequelize/sequelize/issues/311 for a discussion on the subject.
model/product.js:
const Product = sequelize.define("product", {
sku: { type: Sequelize.STRING, allowNull: false, primaryKey: true },
title: { type: Sequelize.STRING, allowNull: false },
availability: {
type: Sequelize.STRING,
allowNull: false,
defaultValue: false,
}
});
model/Attribute.js:
const Attribute = sequelize.define("attribute", {
key: { type: Sequelize.STRING, allowNull: false, primaryKey: true },
productSku: { type: Sequelize.STRING, allowNull: false, primaryKey: true },
value: { type: Sequelize.STRING, allowNull: false },
});
After importing to app.js:
product.hasMany(attribute, { foreignKey: "productSku", sourceKey: "sku" });
attribute.belongsTo(product, { foreignKey: "productSku", targetKey: "sku" });
Explanation:
Product.sku is exported as foreign key to Attibute.productSku. Attribute table has a composite foreign (key + productSku), and a ForeignKey(productSku) from product.sku;

waterline-model.create - primaryKey

I have below model with primary key id:
attributes: {
id: {
type: 'integer',
autoIncrement: true,
primaryKey: true,
unique: true
},
name: {
type: 'string',
unique: true,
required: true
},
}
I am creating model as below:
var model = {
id: undefined,
name: 'name',
};
waterlinemodel.create(model).exec(function(error, result) {});
But it throws below error:
Error (E_UNKNOWN) Encountered an unexpected error] Details: error: null value in column "id" violates not-null constraint
As, 'id' is a primary key, waterline should not look at what is the value of 'id' property.
How to resolve this error? I do not want to remove 'id' because I have created value object for the model and it contains all the attributes of model.I am setting value object property as I need. I do not need to set id property for creation.
I am having exactly the same problem especially with the model configured to use postgresql. With it set to disk or memory, the resource is created but with postgresql the resource is not created with the not null constraint error.
The id is not being set irrespective of whether I set autoPK: true or not. Even setting the id attribute on the model with autoPK:false doesn't work.
As the documentation says :
Will set the primary key of the record. This should be used when autoPK is set to false.
attributes: {
uuid: {
type: 'string',
primaryKey: true,
required: true
}
}
You need to set autoPK : false on your model.
The link to the doc : https://github.com/balderdashy/waterline-docs/blob/master/models.md#primarykey
2019 Answer
jaumard's link to documentation is coming up with a 404 error now, but I think things may have changed since 2015...
Sails.js has base attributes defined in config/models.js which looks something this in a freshly-generated project:
attributes: {
createdAt: { type: 'number', autoCreatedAt: true, },
updatedAt: { type: 'number', autoUpdatedAt: true, },
id: { type: 'number', autoIncrement: true, },
}
Separately, the default primaryKey is set to id. If you wanted to override that, you would need to explicitly specify your new primaryKey in your full model definition. For example, if you wanted to make name your primaryKey you would use something like this:
module.exports = {
primaryKey: 'name',
attributes: {
name: {
type: 'string',
unique: true,
required: true
},
// ...
},
}
Notice I put primaryKey outside attributes. This is important. Your primaryKey will also need the unique and required constraints.
Further, if you want to disable the id column so it is not committed to your database, you must replace id with the value false -- but then you must define a different primaryKey otherwise you will get an error when you start your application. The error shown in the question may be directly related to the fact that the model defined id explicitly as undefined. An example of how to disable id would look something like this:
module.exports = {
primaryKey: 'name',
attributes: {
id: false,
name: {
type: 'string',
unique: true,
required: true
},
// ...
},
}

Mongo Giving 'duplicate key error' on non-unique fields

I am getting a MongoDB error when trying to insert a subdocument. The subdocs already have unique _ids, but an error is being thrown for a different, non-unique field that I don't want unique.
The error in Angular is: "Assets.serial already exist". How can I make this field contain duplicate values, and what is causing the model to assume it should be unique?
Here is my Mongoose model:
'use strict';
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var AssetUrlSchema = new Schema({
name: {
type: String,
unique: false,
default: '',
trim: true
},
url: {
type: String,
unique: false,
default: 'http://placehold.it/75x75',
trim: true
},
}),
AssetSchema = new Schema({
serial: {
type: Number,
unique: false
},
urls: {
type: [AssetUrlSchema],
unique: false,
default: [
{ name: '', url: 'http://placehold.it/75x75' },
{ name: '', url: 'http://placehold.it/75x75' }
]
}
}),
/**
* Item Schema
*/
ItemSchema = new Schema({
name: {
type: String,
default: '',
required: 'Please enter name',
trim: true
},
assets: {
type: [AssetSchema],
default: [],
unique: false
},
property: {
type: Schema.ObjectId,
zd: 'Please select a property',
ref: 'Property'
},
created: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
mongoose.model('Item', ItemSchema);
And here is my 'save' method:
function(){
var i = 0, assets = [];
for (;i < 24;i++) {
assets.push({
serial: 1000+i,
urls: {
name: 'Asset Name ' + i,
url: 'http://placehold.it/75x75?'
}
});
}
item = new Items ({
name: 'FPO',
property: newPropId,
assets: assets
});
return item.$save(
function(response){ return response; },
function(errorResponse) {
$scope.error = errorResponse.data.message;
}
);
}
The first time I insert a document, it works fine. Any subsequent time, it fails with a 400 because the assets.serial field is not unique. However, I am specifically marking that field as unique:false.
The error in the mode console is:
{ [MongoError: insertDocument :: caused by :: 11000 E11000 duplicate key error index: mean-dev.items.$assets.serial_1 dup key: { : 1000 }]
name: 'MongoError',
code: 11000,
err: 'insertDocument :: caused by :: 11000 E11000 duplicate key error index: mean-dev.items.$assets.serial_1 dup key: { : 1000 }' }
POST /api/items 400 14.347 ms - 41
Mongoose doesn't remove existing indexes so you'll need to explicitly drop the index to get rid of it. In the shell:
> db.items.dropIndex('assets.serial_1')
This will happen if you initially define that field unique: true but then later remove that from the schema definition or change it to unique: false.
If you're using MongoAtlas, you can go to the collection -> click 'indexes' -> on the index you want to delete, click 'drop index'
If you are in a dev/prototype mode, simply deleting the actual collection (after changing the unique:true to false for instance), will reset everything and mongoose will allow your duplicates.

Node Js, Sequelize and Jade. How get data from has-many associations between them?

I'm working on a NodeJS+Sequelize+jade web-app. I have a table called box and another one called user. The user has a one-to-many relation with box. What I like to do is list and show in a jade-template all the box details, including the user who owns it.
First I created the tables using sequelize tools
module.exports = function(sequelize, DataTypes) {
var User = sequelize.define('User', {
name: {
type: DataTypes.STRING,
allowNull: false
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true
},
password: {
type: DataTypes.STRING,
allowNull: false
},
dateOfBirth: DataTypes.DATE,
role: {
type: DataTypes.ENUM,
values: ['ADMIN', 'USER'],
defaultValue: 'USER'
}
},{
classMethods:{
associate: function(models) {
User.hasMany(models.Box);
}
})
return User;
};
The same to box:
module.exports = function(sequelize, DataTypes) {
var Box = sequelize.define('Box',{
boxTitle: {
type : DataTypes.STRING,
allowNull: false
},
lifetime: {
type : DataTypes.DATE,
allowNull : false
},
status: {
type: DataTypes.ENUM,
values: ['ACTIVE', 'NOTACTIVE'],
defaultValue: 'ACTIVE'
},
count: {
type: DataTypes.INTEGER,
allowNull : false
}
},{
classMethods:{
associate: function(models) {
Box.belongsTo(models.User);
}
});
return Box;
};
So, when I put some data in the database, I'm trying to print te box information:
each box in boxes
each user in box.users
tr
td= box.getDataValue('boxTitle')
td= user.getDataValue('name')
td= box.getDataValue('lifetime')
td= box.getDataValue('count')
td= box.getDataValue('status')
I did this so far, but I'm getting an error:
Cannot read property 'length' of undefined
I believe the program is not recognizing the association between those two tables, but I'm not sure.
Does anyone knows how can I solve this problem, or maybe to it in a different way?
I would be very grateful if you could help me.

Resources