I have two Models in Sails - Users and Absences. A User has many records of Absences so i'm trying to do a One to Many association. They look like this:
User.js
in attributes:
id: {
type: 'integer',
unique: true,
primaryKey: true,
columnName: 'idx'
},
absences: {
collection: 'absence',
via: 'idxuser'
}
Absence.js
in attributes:
id: {
type: 'integer',
unique: true,
primaryKey: true,
columnName: 'idx'
},
idxuser: {
model: 'user'
}
But when I call a user record I get this error:
Error (E_UNKNOWN) :: Encountered an unexpected error
ER_SP_UNDECLARED_VAR: Undeclared variable: NaN
and the stack trace references the sails-mysql module.
I'm using:
sails 0.10.5
sails-mysql 0.10.6
node 0.10.25
I meet this exception too. But, DB has null value in column. that type of attribute is 'integer'.
First check your values in DB.
Related
I'm using the sequelize module for my node.js mvc project and the query i'd like to execute is the following
SELECT answer_text, isNew, name FROM answer JOIN topic ON answer.topic_id = topic.id
answer_text and isNew are columns of the answer table while name is a column that only exists in the topic table.
How can i have the topic table name column appear in the results next to isNew column so that i can access it easily? Does sequelize provide such a feature or it's my responsibility to format the result?
I've tried to add various things in attributes like 'topic.name' but none worked.
The way i've set up the file structure is based on their documentation Sequelize usage with express
var models = require('../models')
var answers = await models.Answer.findAll({
include: [{
model: models.Topic
}],
attributes: [
'answer_text',
'isNew'
]
})
console.log(answers)
The output of the following is
{ answer_text: 'maybe it is robots',
isNew: true,
Topic:
Topic {
dataValues:
{ id: 830,
mid: 'm.0bjmp5',
name: 'Robot Arena',
description:
'Robot Arena is a computer game made by Infogrames. It features robotic combat similar to that of Battlebots Robotica and Robot Wars. There are a number of different chassis and on top of that there are numerous attachments. Weapons accessories tires and other forms of mobility batteries and air tanks are among the customization choices. A sequel called Robot Arena 2 Design and Destroy was made which allows for total customization of your
robot.',
type: 'cvg.computer_videogame' },
_previousDataValues:
{ id: 830,
mid: 'm.0bjmp5',
name: 'Robot Arena',
description:
'Robot Arena is a computer game made by Infogrames. It features robotic combat similar to that of Battlebots Robotica and Robot Wars. There are a number of different chassis and on top of that there are numerous attachments. Weapons accessories tires and other forms of mobility batteries and air tanks are among the customization choices. A sequel called Robot Arena 2 Design and Destroy was made which allows for total customization of your
robot.',
type: 'cvg.computer_videogame' },
_changed: {},
_modelOptions:
{ timestamps: false,
validate: {},
freezeTableName: false,
underscored: false,
paranoid: false,
rejectOnEmpty: false,
whereCollection: null,
schema: null,
schemaDelimiter: '',
defaultScope: {},
scopes: {},
indexes: [],
name: [Object],
omitNull: false,
sequelize: [Sequelize],
hooks: {} },
_options:
{ isNewRecord: false,
_schema: null,
_schemaDelimiter: '',
include: undefined,
includeNames: undefined,
includeMap: undefined,
includeValidated: true,
raw: true,
attributes: undefined },
isNewRecord: false } }
Please try the following sequelize statement -
var answers = await models.Answer.findAll({
include: [{
model: models.Topic,
attributes: ['name']
}],
attributes: [
'answer_text',
'isNew'
],
raw: true
})
I hope it helps!
Working answer:
Sequelize must be required in order to use [sequelize.col('Topic.name'), 'name'] inside attributes so that we can fetch name column of Topic table and rename 'Topics.name' to name. (Tried models.col but it is not a function)
raw: true is required if you want to get only the columns inside answers[0]
attributes:[] is required inside include because if you don't put it the result will include all the columns from the joined table (Topic).
const models = require('../models')
const sequelize = require('sequelize');
var answers = await models.Answer.findAll({
include: [{
model: models.Topic,
attributes: []
}],
attributes: [
'answer_text',
'isNew',
[sequelize.col('Topic.name'), 'name']
],
raw: true
})
console.log(answers[0])
output:
{ answer_text: 'robot arena',
isNew: 'true',
name: 'Robot Arena' }
I have a Mongoose Schema in which I use subdocuments. Their definitions are:
const vraagSchema = new mongoose.Schema({
vraagNummer: {
type: Number,
required: true,
min: 1
},
vraagTekst: {
type: String,
minLength: 1,
required: true
},
waarde: {
type: Number,
required: true,
min: 1
}
}, { collection: 'vragen' });
const checkSchema = new mongoose.Schema({
checkID: {
type: String,
required: true,
min: 2
},
sessieNummer: {
type: Number,
required: true,
min: 1
},
omschrijving: {
type: String,
required: true
},
vragen: {
type: [vraagSchema]
},
logData: {
type: String,
required: false,
default: ''
}
});
checkSchema.index({ sessieNummer: 1, checkID: 1 }, { unique: true })
Now, when I insert 1 Check item with an empty array for the "vragen" field ("vragen" is Dutch for "questions"), there is no problem.
But when I try to insert another Check item, with slightly different field values (so that it is unique), but also with an empty array "[]" as value for "vragen", I get an error: "MongoError: E11000 duplicate key error collection: demastermind_test.checks index: vragen.vraagNummer_1 dup key: { : null }".
Why is an empty array leading to a duplicate key error? And how can I prevent this?
I then checked what happened if I inserted Check items with non-empty arrays. So I inserted two checks with different field values (so they are unique), where 1 item has a "vragen" array with on "vraag" item in it, and 1 item has a "vragen" array with two "vraag" items in them (where I made sure that the two items had different "vraagNummer" waardes).
And that also leads to the exact same duplicate key error.
What am I missing?
I got this problem fixed. Apparently somewhere when I started working on this, I used an incorrect schema definition (or something), and that error got 'stuck' in de Collection.
I solved the problem by deleting the whole Collection (it currently is a test collection, so that wasn't a problem), and now it works as it should be.
Here is my model definition:
var Notification = vogels.define('Notification', {
tableName: 'notification',
hashKey: 'notification_id',
rangeKey: 'createdAt',
timestamps: true,
schema: {
notification_id : vogels.types.uuid(),
badge: joi.number().integer(),
delay: joi.number(),
action: joi.string(),
body: joi.string(),
tags: vogels.types.stringSet()
},
indexes: [{
hashKey : 'tags',
rangeKey: 'createdAt',
name : 'TagsIndex',
type : 'global'
}]
});
However, when I want to create this table, I get the following error:
Error creating tables: { [ValidationException: Member must satisfy enum value set: [B, N, S]]
message: 'Member must satisfy enum value set: [B, N, S]',
code: 'ValidationException',
time: Thu May 12 2016 14:06:44 GMT-0700 (PDT),
requestId: 'c775c989-c723-4d55-b319-731230a5991b',
statusCode: 400,
retryable: false,
retryDelay: 0 }
The problem is with the index. I remove that, then it works fine.
The error occurred because you cannot use SET data type with Hash/Hash-Range keys.
Only String, Number, and Binary data type can be used for Keys that is what error is suggesting.
Documentation Link clearly mention that we cannot use set.
Hope that helps.
I have a model with an expiration date:
expireAt: {
type: DataTypes.DATE,
allowNull: false
}
I want to create a scope to find the "enabled" records, actually is:
// I add it on associate method, because need to use other model:
QuestionsModel.addScope("enableds", {
where: {
enabled: true // The question is enabled
},
include: [{
model: models.users,
where: {
enabled: true // The author is enabled
}
}]
});
But I don't know how to validate if is expired, I need to discard the expired records (when actual date is higher or equal with expireAt).
Some idea?
I am attempting to create a rallymultiobjectpicker that lists the users of a workspace. However, it does not seem to load any values for the displayField, regardless of what it is set to in the listCfg. The documentation specifies that the default is "Name," to which I have switched around to "FirstName," "ObjectID", "DisplayName," "_refObjectName," etc. No changes seem to be reflected, as the divs that should contain the values for the displayField remain empty. I have checked the objects, and here is an example of what is typically returned (all empty fields are generated and not modified):
->Object
CreationDate: null
Disabled: false
DisplayName: ""
EmailAddress: ""
FirstName: ""
LastName: ""
LastPasswordUpdateDate: null
MiddleName: ""
ObjectID: 1234567890
OnpremLdapUsername: ""
RevisionHistory: ""
Role: ""
ShortDisplayName: ""
Subscription: ""
TeamMemberships: ""
UserName: ""
UserPermissions: ""
UserProfile: ""
_objectVersion: "12"
_p: "2"
_ref: "https://rally1.rallydev.com/slm/webservice/1.33/user/1234567890.js"
_refObjectName: "John D"
_type: "user"
creatable: false
deletable: false
groupSelected: "Available"
matchedText: undefined
updatable: true
__proto__: Object
Here is an example of the code used:
Ext.widget('rallymultiobjectpicker', {
modelType: 'user',
fieldLabel: 'Owners',
listCfg: {displayField: "DisplayName", autoScroll: true},
stateful: false,
labelWidth: 50,
});
EDIT: Using a similar configuration as the one listed in the answer below, this issue has arisen again in 2.0p3. There is no option text shown, despite having the displayField specified in the listCfg. I should also note that the filters/customQuery seem to be completely broken, as they don't function to limit the data set I have in another rallymultiobjectpicker.
You must specify a data store configuration that fetches the displayField from the server. You'll have to specify the entire store configuration, not only the fetch parameter. You'll also have to pass a config option for the filterFieldName for the auto complete functionality to work properly. An example configuration is below:
Ext.widget('rallymultiobjectpicker', {
modelType: 'user',
fieldLabel: 'Owners',
filterFieldName: 'DisplayName',
storeCfg: {
autoLoad: false,
fetch: 'DisplayName',
pageSize: 200,
sorters: [
{
property: 'DisplayName',
direction: 'ASC'
}
],
remoteGroup: false,
remoteSort: false,
remoteFilter: false,
limit: Infinity
},
listCfg: {
displayField: 'DisplayName'
},
stateful: false,
labelWidth: 50
});