Create scope by time range on sequelize - javascript

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?

Related

How to write formula in ORDER using fields from subquery

I need to implement sorting on computed data from a subquery. There is a request like this:
const res = await db.order.findAndCountAll({
limit: 10,
offset: (page - 1) * 10,
distinct: true,
order: [[db.sequelize.literal('product.taxes * product.count'), 'ASC']],
where,
include: [
{ model: db.location },
{ model: db.address },
{
model: db.order_product,
as: 'products',
required: true,
include: [
{
model: db.product,
include: [{ model: db.location }],
},
],
},
],
});
This code is not working. I get the error:
missing FROM-clause entry for table "product"
In line:order: [[db.sequelize.literal('product.taxes * product.count'), 'ASC']], i want to use to calculate the fields that are in the db.product model which i am accessing in a sub-sub-query. Moreover, this sub-sub-query will return an array, and I need to execute (db.product.amount * db.product.price) for each element of the array and then add up all the resulting products. How to describe this formula in "order"?
Maybe I chose the wrong path. What is the best way to sort by calculated data from a subquery?

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.

Chain relationship in keystone.js

var leaves = new keystone.List('leaves');
leaves.add({
createdBy: {
type: Types.Relationship,
ref: 'user-datas',
initial: true,
label: 'Submitted By',
},
});
var userData = new keystone.List('user-datas');
userData.add({
user_id: {
type: Types.Relationship,
ref: 'Employees',
},
});
var Employees = new keystone.List('Employees');
Employees.add({
name: {
type: Types.Name,
required: true,
index: true,
initial: true,
},
});
I have 3 models/list: leaves,user-data, Employees.
So when in admin panel when I want to add a leave it shows Object id of record from user-data.
But is there any way to show name from Employees when entering a new leave. but the still refer to user-data?
I need to show user's name instead of the user ID as shown in the image below.
When you add the relationship for the leaves, you can do something like this:
submittedBy: {type: Types.Relationship, ref: 'User', many: false},
Hope this help. If not, please post more details like the model declaration.
You can achieve it by using relationship.

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