ValidationException with Indexing stringSet in Vogels for DynamoDB - javascript

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.

Related

Sequelize how to return column of joined table in the results

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' }

Why "duplicate key error" when inserting subdocument arrays?

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.

Stringify and parse an object literal

I have this object literal
var rides = {
brand: {
type: String,
label: "搜尋",
max: 100
},
model: {
type: String,
label: "Tìm kiếm",
max: 100
},
fueltype: {
type: String,
label: "Пошук",
allowedValues: ['Petrol', 'Diesel', 'Hybrid', 'Electric'],
},
bodystyle: {
type: String,
label: "بحث",
allowedValues: ['Convertibles', 'Coupes', 'Hatchbacks', 'Vans', 'Sedans', 'Suvs', 'Trucks', 'Wagons'],
optional: true
},
topspeed: {
type: Number,
label: "חיפוש",
optional: true
},
power: {
type: Number,
label: "Power (HP)",
optional: true
}
};
which i have stringfied in this way
var ss = JSON.stringify(rides);
However, for what I am doing to work, I need to get the object i stringfied exactly the way it was before i stringfied
Thi is what it looks like https://jsfiddle.net/y37crsvd/1/
Object { brand: Object, model: Object, fueltype: Object, bodystyle: Object, topspeed: Object, power: Object }
How can I stringify the object literal so as to show the nested object properties?
You can't stringify() functions, unless you use a custom revive parameter on JSON.parse(), and a custom mapper parameter on JSON.stringify(). Or, define Function.prototype.toJSON to get the "plain" JSON.stringify() to work with functions like window.Number and window.String.
The xx in the fiddle does contain the nested object properties, it's the console which requires you to expand the inner properties as well...
When you log xx the console shows the object and allow you to expand the properties. It also puts the properties in alphabetic order.
If you do a JSON.stringify(xx) you will see exactly the same string as you input in the first time (properties in the same order...).

Sails js Undeclared Variable: NaN when modelling associations

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.

jquery library "uriAnchor" - I can't figure out how to set up the validation config

I'm reading a book "single page web application" written by "Michael S. Mikowski".
In chapter3, there is a code using jQuery library "uriAnchor".
the book doesn't provide information much about this jquery library, so I took a look at the document of uriAnchor on github.
https://github.com/mmikowski/urianchor
This "uriAnchor" has a method "configModule()" that sets up the rule for validation.
I read the instruction for this method but I couldn't understand how to set up the config object.
This is the code from the instruction page.
Validation:
As of 1.0, the ability to optionally check the validity of the Anchor
against a schema has been included. Since we don't expect the
allowable schema to change during run-time, we use a module
configuration to set the schema, like so:
$uriAnchor.configModule({
schema_map : {
page : { profile : true, pdf : true },
_page : {
uname : true,
online : { 'today','yesterday','earlier' }
},
slider : { confirm : 'deny' },
_slider : { text : 'goodbye' },
color : { red : true, green : true, blue : true }
}
});
I believe this configModule method set up the validation rule for urls like this below.
/#!page=profile:uname,true|online:today&slider=confirm:text,goodbye&color=red
but, what are these!?
for example,
page : { profile : true, pdf : true },
what does these boolean mean and where and how are they used?
They don't even show up in the url.
slider : { confirm : 'deny' },
and also, what is this!??
what is the role of the value "deny" for this method??
online : { 'today','yesterday','earlier' }
and what is this!? the value is not even an array!!
I have no idea.
I tried changing these setting and see what kind of different it would make but I couldn't figure out.
If you are familiar with this jquery library, please answer my question!
Thank you so much!!
I found this book "single page web application" is very stressful to read...
I've been spending 2 days to understand chapter 3...
In his configModule example, which defines acceptable url variables and values there are two mistakes:
// wrong
$uriAnchor.configModule({ ...
// fixed
$.uriAnchor.configModule({ ...
// wrong
online: { 'today','yesterday','earlier' }
// fixed
online: { 'today': true, 'yesterday': true, 'earlier': true }
The schema actually follows a consistent pattern: Property names in the schema with values that evaluate to true define acceptable values for their objects. Any other values cause an error.
The following defines 1 fish, 2 fish and 333 as acceptable values for online:
online: { '1 fish': true, '2 fish': true, 333: true }
The following explicitly defines 1 fish and 2 fish as acceptable values for online, and w, x, y and z as NOT acceptable:
online: { '1 fish': true, '2 fish': 'trout',
w: false, x: 0, y: '', z: undefined }
The value trout makes 2 fish a valid value for online because trout is a non-empty string, which javascript evaluates as true. Mikowski's examples confirm: 'deny' and text: 'goodbye' are equally valid but equally confusing. Sticking with true and false would be more clear.
Values not defined as properties in the schema are also disallowed, so technically there's no need to include them and set them to false in the schema except for development purposes or self-documentation.
Consider this schema example:
$.uriAnchor.configModule({
schema_map : {
page : { profile : true, pdf : true },
_page : {
uname: true,
online: { '1 fish': true, '2 fish': true, 'red fish': false }
},
slider : { confirm : true },
_slider : { text : true, what : true },
color : { red : true, green : true, blue : false }
}
});
(notice below that uname: true is not necessary)
Some example setAnchor calls, and the URIs they generate:
// #!page=profile:uname,steve
$.uriAnchor.setAnchor({
page: 'profile',
_page: {
uname: 'steve'
}
});
// #!page=pdf:uname,joe|online,1%20fish&slider=confirm:text,hello&color=red
$.uriAnchor.setAnchor({
page: 'pdf',
_page: {
uname: 'joe',
online: '1 fish'
},
slider: 'confirm',
_slider: {
text: 'hello'
},
color: 'red'
});
// #!page=pdf:uname,joe|online,1%20fish|nothing,zero&slider=confirm:text,hello|pretty,123&color=red
$.uriAnchor.setAnchor({
page: 'pdf',
_page: {
uname: 'joe',
online: '1 fish',
nothing: 'zero'
},
slider: 'confirm',
_slider: {
text: 'hello',
pretty: 123
},
color: 'red'
});
Notice that the dependent variables "nothing" and 'pretty" are not defined in the schema, but they work anyway.
Maybe this is a bug - I have no idea, but dependent variables are accepted whether they are in the schema or not.
Technically the only time you have to explicitly define a dependent variable is so you can define acceptable values for it, as in "online". Otherwise, self-documentation seems to be the only benefit.

Categories

Resources