Can't add new attributes to existing model sails.js - javascript

I'm quite newbie in sails.js. I need to add fields to an existing model in sails js.
Here it is
module.exports = {
attributes: {
id: {
columnName: 'id',
type: 'integer',
autoIncrement: true,
primaryKey: true,
unique: true
},
username: {
columnName: 'username',
type: 'STRING',
required: true,
},
userLevel: {
columnName: 'user_level',
type: 'integer',
required: true,
defaultsTo: 1
},
...
But as soon as I add the fields in my model js like
newAttribute: {
columnName: 'new_attribute',
type: 'integer',
required: true
}
I get an error "E_UKNOWN".
To be more precise, when I try to login with updated model, I get this message:
rr {"data":{"err":{"error":"E_UNKNOWN","status":500,"summary":"Encountered an unexpected error","raw":{"code":"ER_BAD_FIELD_ERROR","errno":1054,"sqlState":"42S22","index":0}}},"status":401,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"data":{*email and password here*},"url":"auth/login","headers":{"Accept":"application/json, text/plain, */*","Content-Type":"application/json;charset=utf-8"}},"statusText":"Unauthorized"}
Appreciate your help.
UPD It's working if I set NODE_ENV to development. May it could be the problem with connection.js file?

Seems that I've found the solution of my problem. At first I set NODE_ENV to development, and, I guess, the tables were created. Then I change NODE_ENV to production. And now it's working without odd errors.

Related

Sequelize: Unknown column *.createdAt in 'field list'

I've come across this problem several times in the past and have read a number of solutions. Before I go through them again, I was hoping someone could explain exactly what the problem is - because despite eventually fixing it, I never really understand why
The error:
original: Error: Unknown column 'job.createdAt' in 'field list'
What I assume is the source (as I just added it):
[Sequelize.fn('date_format', Sequelize.col('job.createdAt' ), '%d/%m/%y'), 'jobDate']
The error suggests that createdAt isn't a column in the jobs table - several solutions suggest defining createdAt in your model (which I'd already done).
What also confuses me is that in workbench I can run the query:
SELECT * FROM test.jobs ORDER BY test.jobs.createdAt;
and it works, and that I don't have this problem with the equivalent Company attribute.
Job Model:
const Job = sequelize.define('job', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true
},
title: {
type: Sequelize.STRING,
allowNull: false
},
...
createdAt: {
type: Sequelize.DATE(3),
allowNull: false,
},
updatedAt: {
type: Sequelize.DATE(3),
allowNull: false,
}
});
The options object for the query:
const options = {
include: [
{
model: Job,
attributes: [
'id',
'title',
// ...
'createdAt',
[Sequelize.fn('date_format', Sequelize.col('job.createdAt' ), '%d/%m/%y'), 'jobDate'],
]
},
],
attributes: [
'id',
'name',
'createdAt',
[Sequelize.fn('date_format', Sequelize.col('company.createdAt' ), '%d/%m/%y'), 'companyDate'],
],
order: [[ orderField, orderDirection ]],
distinct: true
}
Workbench showing the column:
As far as I can tell the relevant part(?) of the actual sql query looks right too
`jobs`.`createdAt` AS `jobs.createdAt`, date_format(`job`.`createdAt`, '%d/%m/%y') AS `jobs.jobDate`,
Appreciate any help

Duplicate key error collection with unique field

I am getting a MongoDB error when trying to insert a document without nickname second time. The document already have unique field and non required.
Here is my Mongoose model:
var schema = new Schema ({
username: {
type: String,
required: false
},
nickname: {
type: String,
required: false,
unique: true,
trim: true
},
status: {
type: String,
required: false,
trim: true,
minlength: 1,
maxlength: 100
},
avatar: String,
online: {
type: Boolean,
default: false
},
created: {
type: Date,
default: Date.now
},
device: {
type: ObjectId,
ref: 'Device',
required: false
},
createdRooms:[{
type: Schema.Types.ObjectId,
ref: 'Room'
}],
facebook: {
facebookToken: {
type: String,
required: false,
trim: true,
unique: false
},
facebookId: {
type: String,
required: false,
trim: true,
unique: false
}
}
},
{
toObject: {
virtuals: true
},
toJSON: {
virtuals: true
}
});
For the first time, the document without a nickname is added to the database, but when I want to save another document without a nickname, I get an error:
MongoError: E11000 duplicate key error collection: grooptag.users index: nickname_1 dup key: { : null }
So I looked up "MongoDB not required but unique" and I found this: mongoDB/mongoose: unique if not null
It seems you need to use sparse: true instead of required: false to get what you want.
Edit: Reading up the MongoDB documentation on sparse indexes, however, I was redirected to partial indexes which seem to be the way to go from MongoDB 3.2 onward: https://docs.mongodb.com/manual/core/index-partial/#index-type-partial
The problem is that while the documentation clearly states:
Partial indexes represent a superset of the functionality offered by sparse indexes and should be preferred over sparse indexes.
It does not seem to be true for sparse and unique indexes, since they also state on the same page:
A partial index with a unique constraint does not prevent the insertion of documents that do not meet the unique constraint if the documents do not meet the filter criteria.
Way to contradict themselves... :/

Sails.js with mongodb design

just starting out in sails.
Currently I have a User Model set up. I also have another Founder Model to store information specific to Users who are also Models.
attributes: {
companyName: {
type: 'string',
required: true
},
tagLine: {
type: 'string',
required: true
},
location: {
type: 'string',
required: true
},
market: {
type: 'string',
required: true
},
psName: {
type: 'string',
required: true
},
psDesc: {
type: 'string'.
required: true
}
}
So my question in the FounderController...would inputting the unique id for the user from User for the database be implemented in the models or in the controller? The Founder model will essentially create it's own unique id.
My first approach would to basically find the ID from the User documents, store it into a variable, update the Founder document's id field with the user id?
I felt this isn't very efficient. Thanks.

Sails.Js - Simple Exercise with 2 Relations on the ORM

I'm new to Sails.js and Node.js, so if i'm asking a simple question please forgive me.
I'm doing an API that must have a database, and i wanted to implement MySQL because i have some relations between tables. So i wrote the relational model by hand, like it is on the figure:
And i tried to implement is using sails.js, but for some reason i can't get the relation Level to Score working while the User-Score relationship is working fine.
Here are my models:
User.JS
module.exports = {
attributes: {
name:{
type:'string',
required: true
},
address:{
type: 'string'
},
email:{
type: 'string',
email:true,
unique: true,
required: true
},
encryptedPassword:{
type: 'string'
},
tranusertoscore:{
collection:'scores',
via: 'transcoretouser'
}
}
}
Level.js
module.exports = {
attributes: {
lvl_name:{
type: 'string',
required: true
},
tranleveltoscore:{
collection: 'scores',
via: 'transcoretolevels'
}
}
};
and finally
Score.js
module.exports = {
attributes: {
lvl:{
type: 'string',
required: true
},
score:{
type: 'integer',
required: true
},
transcoretouser:{
model: 'user'
},
transcoretolevels:{
model: 'level'
}
}
};
So, can you guys tell me what i'm doing wrong?
Sorry to take your time if the answer is easy, but i tried to follow documentation and search about the subject and didn't find any relevant answers.

Sails.js model unique property doesn't work in production env

I am fairly new to sails and have followed a simple tutorial to create a REST api. I have created a model:
module.exports = {
schema: true,
attributes: {
name: {
type: "string",
unique: true,
required: true
},
role: {
type: "string",
required: true
},
group: {
type: "string",
required: true
},
email: {
type: "string",
unique: true,
required: true
},
telephoneNumber1: {
type: "string",
required: true
},
telephoneNumber2: {
type: "string",
}
}
};
The model contains some unique fields. I tested this out locally using both the sails localDisk and a real mongo DB running locally and everything was working i.e. when trying to add a duplicate it was rejecting it.
I then deployed to heroku and put in all the heroku config for the MongoLab and Redis. When testing I found that I could view all the entries using the index endpoint that I had created and I could also create new documents using the create endpoint. I then added a duplicate entry to the DB through the create url and found that it was allowing it and I was ending up with a load of documents that were identical.
I am using the 'sails-mongo' adapter. Is there something I need to do with the prod DB to apply the rules?
Thanks
Alex

Categories

Resources