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
},
// ...
},
}
Related
I was working on a project where we can create a form like google forms and get responses from users, and then we can view those responses in the admin panel.
My English is not that good I tried my best to explain the problem!
I am using MERN Stack so I was tucked into a problem related to how to save the questions and record the responses in MongoDB in a standard way in objects and arrays.
currently I added this as a form model :
const formSchema = new Schema({
usererId: { type: Schema.Types.ObjectId, ref: 'User' },
title: { type: String, required: true },
description: { type: String},
username: { type: String, required: true },
password: { type: String, required: true },
isEnabled: { type: Boolean, default: true },
expiresOn: { type: Date, default: null },
fields: [
{
title: { type: String, required: true },
placeholder: { type: String, required: false },
type: { type: String, required: true },
required: { type: Boolean, required: true },
options: [
{
title: { type: Object, required: true },
priority: { type: Number, default: 0, required: true }
}
],
priority: { type: Number, required: true, default: 0 },
enabled: { type: Boolean, default: true, required: true }
}
],
}, {
timestamps: true
})
and form responses :
const formResponseSchema = new Schema({
digitalFormId: { type: Schema.Types.ObjectId, ref: 'Form' },
isVerified: { type: Boolean, default: false },
formResponse: [{ type: Object, required: true }],
}, {
timestamps: true
})
I don't know if this approach is good, I myself like it's not like a standard one and I m confused, Someone please tell me how should I do it and what is the perfect way of doing it,
If you have a problem understanding what I am saying just tell me simply how a google form works in the backend from API view, like question ID server-side validation and response submit, that time what type of request is sent to the server, something like this !
If you don't mind please take out some time and write a brief approach of what type of Schema should I use and how should I save them.
Something more important is what approach to use while checking the form response data coming from the client to validate on server-side means on express API, like {questionId: idofquestion, value:'Value of the response of the particular question'}, later checking the question label and all other things with the form questions and all validation rules to fetch from them and check, but I don't know how to do that It's really confusing for me.
Thanks in Advance for the help! ❤️
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;
I am working with Sequelize and I'm trying to insert one row into my User Column. However, I keep getting the following error:
Unhandled rejection SequelizeDatabaseError: Invalid object name 'User'.
I am connecting to a MSSQL server. I know that I have the basic connection right because I can run sequelize's plain queries via sequelize.query without issue. My suspicion is that I'm not specifying the schema or database correctly.
My model definition:
var user = sequelize.define("User", {
ID: {
type: Sequelize.INTEGER,
unique: true,
autoIncrement: true
},
FirstName: {
type: Sequelize.STRING
},
LastName: {
type: Sequelize.STRING
},
CreateDate: {
type: Sequelize.DATE
},
UpdateDate: {
type: Sequelize.DATE
}
},{
tableName: 'User',
timestamps: false,
freezeTableName: true
});
My attempt to use the model to create/INSERT a row into my pre-existing database.
User.schema('Core');
User.create({ ID: '1', FirstName: 'Bobert', LastName: 'Jones'}).then(function(user) {
console.log(user.get({
plain: true
}))
});
When I used Sequelize's plain SQL to accomplish this I DID have to include the schema aka "insert into Core.User". Am I not specifying the schema correctly? I have tried adding it to my initial connection definition by adding "schema: 'Core'," before dialectOptions.
you can specify schema in your sequelize constructor:
var sequelize = new Sequelize("db",
"user",
"pass", {
host: "localhost",
port: "1206",
dialect: "mssql",
define: {
schema: "core"
}
});
However, according to their code what you are doing appears correct. In the sequelize constructor you can also turn logging on (logging: true). Logging should output the exact sql that is being constructed.
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'
});
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.