Where IN concat with sequelize - javascript

I am trying to make a clause in which I create a concatenation between two fields of my table in DB2.
Where inMunicipio is an arrangement of municipalities concatenated with department.
['08001', '08137', '08141']
In a normal query it would be like this:
SELECT
*
FROM
SALUD.SF_VISITAS SV
WHERE SV.DPTO || SV.MUNICIPIO IN(${inMunicipio.toString()})
This way works perfect, however I have not been able to perform the same query in sequelize. I am trying this way;
let whereMunicipios = sequelize.where(Sequelize.fn("concat", Sequelize.col("DPTO"),
Sequelize.col("MUNICIPIO")), {in: inMunicipio})
whereFilter = {...whereFilter, ...whereMunicipios}
const resultado = await Visitas.findAll({
attributes: camposVisita,
where : whereFilter
})
I would appreciate your help or any guidance. Thank you.

Related

How to perform mongoose deleteMany() with query operators?

I want to delete X number of posts starting from the most recently created for a specific user.
How can I apply this logic using mongoose so that I can perform just ONE database operation instead of first having to query for these posts and remove them one by one?
I am finding using the query and projection operators with the $ very confusing, any help would be appreciated.
Below I added pseudo code on how it should to work.
Thank you!
const userId = "123456"
const deleteCount = 6
const deletedPosts = await Post.deleteMany({
.where { userid == userId) }
.sort({createdAt: -1}) // delete by most recent
.limit(deleteCount) // only delete 6 (most recent) posts
}, {new: true}) // return results of operation
console.log(deletedPosts.deletedCount) // -> should be "6"
You can't set a limit when using deleteMany or findAndModify. So, if you want to precisely limit the number of documents removed, you'll need to do it in two steps.
db.getCollection('users').find({}, {class : 4}) .limit(2) .sort({StudentAge: -1}) .toArray() .map(function(doc) { return doc._id; }); //returns the array of id's
db.getCollection('users').deleteMany({_id: {$in: [ "s3", "s4" ]}})//put the array of id's

get a range of numbers from sql column of type varchar

I have a postgres server running with one column (say marks) of type VARCHAR(255), but is supposed to have numbers, like if i do a select *.. query , i will get ['100','50','21','14'...] etc.
i would like to run a range query on it, like user passes [10,30] and gets ['21','14'] as result. I think this would require casting at the time of running the BETWEEN query, but i cannot get it to work properly.
I am using sequalize.js which is generating the following query:
SELECT "id"
FROM "token_attributes" AS "token_attributes"
WHERE "token_attributes"."attributesDirectoryId" = 3
AND CAST('token_attributes.attributeValue' AS INTEGER) BETWEEN 10 AND 30;
on server also this query seems to fail. the sequalize query that is being created is :
{
where: {
attributesDirectoryId: 3,
attributeValue: Where { attribute: [Cast], comparator: '=', logic: [Object] }
},
attributes: [ 'id' ]
}
i have used the following code to create the where condition (cast and where were imported from sequelize):
let whereFilter ={}
let value = where(cast(`${tableName}.attributeValue`, 'integer'), {[Op.between]: rangeAsInt})
whereFilter['attributeValue'] = value
so this is basically calling table.findAll({where:whereFilter}) I am not sure how to either make sequelize create a correct sql api or what the actual correct SQL api would be. can anyone help?
found the issue, i missed the sequilize.col function :
let whereFilter ={}
let value = where(cast(col(`${tableName}.attributeValue`), 'integer'), {[Op.between]: rangeAsInt})
whereFilter['attributeValue'] = value
and the query would be :
SELECT "id"
FROM "token_attributes" AS "token_attributes"
WHERE "token_attributes"."attributesDirectoryId" = 3
AND CAST("token_attributes"."attributeValue" AS INTEGER) BETWEEN 10 AND 30;

Parse.com match all pointers on array in given relation column

I have Conversation classes with a members relation attribute pointing to User class.
This members attribute consists of people belong to a particular conversation.
Now I want to query if given array of pointers User is part of particular conversation given that all elements must match.
I tried to use containsAll("members", users) but instead got undefined.
containedIn() worked but it returned all matching conversation that has at least one matching User in array.
equalTo("members", users) was not working as well and note that the users variable is array of pointers and not just array of strings objectId, but I also tried that one but got me nowhere.
Here's what I tried:
* Created AND queries where userRelationQuery.equalTo('member', ParseUser1) up to N number of users and still didn't work
Here's my solution but feel free to correct this for improvement
const members = getMembers();
let query = new Parse.Query("Conversation").equalTo(
"members",
members[0]
);
for (let i = 0; i < members.length; i++) {
query = new Parse.Query("Conversation")
.matchesKeyInQuery("objectId", "objectId", query)
.equalTo(
"members",
members[i]
);
}
const chat = await query.includeAll().first();
This should work for you
var conversationClass = Parse.Object.extend('Conversation');
var conversationQuery = new Parse.Query(conversationClass);
return conversationQuery.first()
.then(queryResult => {
var userRelationQuery = queryResult.relation('members').query(); //You can get all users releated to this conversation
//userRelationQuery.equalTo('username', 'Blank0330') // Or you can add more conditions
return userRelationQuery.find()
.then(users => {
return users; //This is your releated users
});
});
For more information about Parse-JS-SDK Relation

How to get the intersection of 2 mysql queries?

Suppose I have a MySQL table which looks like this:
Each job in the table contains 3 tasks.
How can I get all the JobIds whose taskA is in Done state and taskB is in New state?
In my case, I want a query which returns qwert, and zxcv.
I've come up with this query:
select JobId from MyTable where TaskSeq=0 and TaskState='Done'
intersect
select JobId from MyTable where TaskSeq=1 and TaskState='New';
but my version of MySQL doesn't support the intercept operator.
My ultimate goal is to write the query in sequelize. But I think I should know the MySQL query first so that I can create a sequlize query.
And I also wish that the sequlize query can be done in 1 function instead of multiple functions concatenated with then.
Here's the SQL Fiddle to help you try the table.
You could just use a join:
select mt.JobId
from MyTable mt
join MyTable mt2 on mt2.JobId = mt.JobId
where mt.TaskSeq = 0 and mt.TaskState = 'Done' and mt2.TaskSeq = 1 and mt2.TaskState = 'New'
Here's an attempt at Sequelize on this query, however this is a guess. Hopefully it gives you something to work with:
MyTable.findAll({
attributes: ['JobId', 'TaskSeq', 'TaskState'],
include: [{
model: MyTable,
attributes: ['JobId', 'TaskSeq', 'TaskState'],
where: {
JobId: Sequelize.col('MyTable.JobId'),
TaskSeq: 1,
TaskState: 'New'
}
}],
where {
TaskSeq: 0,
TaskState: 'Done'
}
});

Populate SUM of column from accessdb into textbox using javascript

I have a webpage with a few textboxes; and an access database with columns that contain numeric data, dates and user id's.
I need help to SUM a column WHERE the date is >= 1/1/2013.
Lets just say i cant use server side scripting with my current setup. I need this done only by JS or jquery.
Here is the code i came up with to retrieve the sum. but the textbox is returned with this value "[object]".
Also, im not sure how to write the "WHERE" condition.
I'm sure its something simple im missing. any help will be greatly appreciated!!
function retrieve_records() {
var adoconn = new ActiveXobject("ADODB.Connection");
var adoRS = new ActiveXobject("ADODB.Recordset");
adoconn.Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source='database.mdb'");
adoRS.Open("Select SUM(database_column_name) As Total FROM tablename", adoconn, 1, 3);
textbox1.value = adoRS;
adoRS.close();
adoconn.close();
}
Thanks!
Marvin.
This is cobbled to gether from a knowledge of ADO and Access rather than Javascript.
var cmd = new ActiveXObject("ADODB.Command");
cmd.ActiveConnection = adoconn;
var strSQL = "Select SUM(database_column_name) As Total FROM tablename WHERE aDate=?";
cmd.CommandText = strSQL;
var param = cmd.CreateParameter("adate", 7, 1,, "2013/12/31");
cmd.Parameters.Append(param);
var adoRS = cmd.Execute();
textbox1.value = adoRS.Fields(0)
Fields(0) because you only have one field, Fields('Total') should also work. The date is a string above, it should work with Access, but you might like to use a proper date.

Categories

Resources