Sequelize "WHERE" Clause in subqueries - javascript

I'am trying to build my query using sequelize, in the where clause I need to give the conditional value from my front-end so i did it like this :
getResults(req) {
return parm
.findAll({
attributes: [
sequelize.literal('DISTINCT "id"')
],
where : {
name: req.query.parm.replace(/"/g, '').split(',')
} ,
raw: true
});
}
and it's working!
but now I need to write a subquery including where clause:
something like this :
SELECT tab1.name FROM
(SELECT name FROM "MYTABLE"
WHERE id = (value from the front-end) AND name IN (values from front-end)
) as tab1
Here is what i have tried :
getTest(req) {
if (req.query.parm != null) {
return parm .sequelize.query('SELECT id FROM "table_base" where id = $mid ); ',
{ type: sequelize.QueryTypes.SELECT ,
bind: { mid: [req.query.parm.replace(/"/g, '').split(',')] }} );
}
},
i tried to use raw query and i tested the binding parameters but i get this error when i execute this testing query :
Executing (default): SELECT id FROM "table_base" where id = $1 );

The answer to your question is YES it is indeed possible! SQL can pretty much do anything even if you are using sequelize. If you write the subquery and it doesn't work just post it back here so people can take a look and debug. Thanks

Related

Using multiple query conditions in MongoDB's UpdateOne statement

I am trying to update a query using 'updateOne' with multiple conditions.
when I put a single Codition it works fine.
or when I ordered the highly unique identifier first in condition, then it works fine.
but when I change it's order it seems jammed and inserting multiple document with different _id.
follwoing is my Javascript code code.
const posts = await loadPostsCollection();
await posts.updateOne(
{
"timestamp" : jsoned_body.timestamp ,
"transactionID" : jsoned_body.transactionID ,
"deviceSN" : jsoned_body.deviceSN ,
},
{
$set:
{
"transactionID": jsoned_body.transactionID,
"deviceName": jsoned_body.deviceName,
"deviceSN": jsoned_body.deviceSN,
"userID": jsoned_body.userID
}
},
{ upsert: true }
)
async function loadPostsCollection() {
const client = await
mongodb.MongoClient.connect(`mongodb://${config.DB_IPAddr}:${config.DB_PortNo}/tms`, {
});
return client.db('tms').collection('transactionLogs');
}
what am I missing?

Update database entry using mongoose

Hello i am using mongoose.
I have built this query that finds my desired project :
const projects = await ClientManagers.findOne({'project.contactPerson.work_email' : 'testing#email.com'} , { 'project.$.companyName': 1 });
this returns an object from my database like this :
{
'projectName' : 'x',
'companyName' : 'x bv'
}
How can i update the company name to be 'Y bv' instead of 'x bv'.
Assuming this is your document structure,
{
"_id" : ObjectId("5f2ae5a4b1549ac0460920dd"),
"projectName" : "A",
"project" : [
{
"companyName" : "T1",
"contactPerson" : {
"work_email" : "t1#gmail.com"
}
},
{
"companyName" : "T2",
"contactPerson" : {
"work_email" : "t2#gmail.com"
}
}
]
}
Single Update updateOne()
If you know email will be unique and want to update single document then use updateOne().
first is query part to find condition, email t1#gmail.com
second is set/update part, here $ is for array because project is an array, update companyName to T1 Company
await ClientManagers.updateOne(
{ 'project.contactPerson.work_email': 't1#gmail.com' },
{
$set: { "project.$.companyName": "T1 Companmy" }
}
)
Multiple Update updateMany()
If email is not unique and want to update everywhere then use updateMany(), it will update every matching documents.
await ClientManagers.updateMany(
{ 'project.contactPerson.work_email': 't1#gmail.com' },
{
$set: { "project.$.companyName": "T1 Company" }
}
)
Not suggesting update() method to use, because its deprecated in mongoose and will give Deprecation Warnings
, this function is replaced with updateOne(), updateMany() and replaceOne() methods.
Good start. Mongo has better documentation with examples. I suggest you to refer that also.
use update
db.collection.update({companyName:'x bv'}, {"$set":{"companyName":y}})
Mongo is case sensitive. So name should match exactly.
update updates one document. To update multiple, use updateMany or multi:true option with update or findOneAndMondify for one update for find and update case.

Making a JOIN WHERE key IN(SELECT key FROM...) using Sequelize.js

Im a noob in Sequelize.js and somewhat less in Angular but must solve a problem in which I want to use a subquery as a condition of a JOIN. I paste some examples below because code says more then words.
SQL
INNER JOIN table ON table.key IN(SELECT current_key FROM historysnake WHERE original_key IN(
SELECT original_key FROM historysnake WHERE current_key = table.key)
AND historysnake.model = 'tablename')
The question is: How can I put above query into a Sequelize object? Something like:
Sequelize.js
var foo = sequelize.define('foo', {...}, {
classMethods: {
associate: function(models) {
foo.hasMany(...)
}
}
});
Ok, here's an example, which assumes that PK of PatientEvents is the original_key on all the history rows:
PatientEvents.hasMany(HistorySnake, {foreignKey : 'original_key'});
PatientEvents.findAll({
include: [{
model: HistorySnake,
required : true, // true = INNER JOIN but you might need outer join to see events with no history
where : { modelName : 'PatientEvents' } // as needed
}],
where: { patient_name : 'xyz' } // as needed
})
I figured it out. I'm not really sure if #KenOn10's answer would've worked. I'm too much of a noob on this subject for that but thanks for the answer anyway.
I ended up specifying my own 'on' clause like this.
models.Aim.find({
include: [{
model: models.ObjectiveReport,
required: false,
where: ['ObjectiveReports.report_entrydate >= ?', show_date],
on: {
aim_id: sequelize.literal('aim.aim_id IN(SELECT current_key FROM historysnake WHERE original_key IN(SELECT original_key FROM historysnake WHERE current_key = aim.aim_id) AND historysnake.model = "aim")')
})
...

Firebase orderByValue().equalTo() is not a function (Node JS)

My database has the following structure:
"groupA" : {
"applications" : {
"applicationID_132" : {
"status" : "accepted"
},
"applicationID_423" : {
"status" : "declined"
},
"applicationID_562" : {
"status" : "accepted"
}
}
}
I am trying to retrieve the snapshot of applications with "accepted" status (to be able to skip fetching all applications) by:
return admin.database().ref('groupA').child('applications').orderByValue('status').equalTo('accepted')
.once('value')
.then(acceptedApplicationsSnapshot => {
Doesn't seem to work, tried orderBy and orderByValue as well. What might be missing or what is the better way to handle this case?
Thank you for any help!
Try using child.orderByChild().value()
In your case:
return admin.database().ref('groupA').child('applications').orderByChild('status').equalTo('accepted')
.once('value')
.then(acceptedApplicationsSnapshot => {
You could use orderByValue() as well, but first you would need to get the Reference which you want to order - function does not accept parameter.
How to use orderByValue()?
.child(..) returns a Reference in your case that is applications if you want to use orderByValue than you would need to get reference to 'status' before doing that, eg:
admin.database().ref('groupA').child('applications').child('status').orderByValue() and then you would apply one of the data filtering methods eg.
.equalTo('accepted')...

Mongoose not returning, but mongo shell is

I'm using mongoose on my node app, and I want to get a seller by its email:
getSellerByEmail : function(email,next){
var Seller = mongoose.model('Seller');
console.log(inspect(email));
Seller.findOne({'email' : new RegExp(email, 'i')}, function(seller){
next(seller);
});
}
When I try to login, mongoose does not return the new user. But when I try to create another user with the same email, the server executes this function correctly and it returns the new user.
Also tried with {'email' : email} and It returns null, but when I do this query on mongo shell, it returns correctly.
db.sellers.findOne({email : 'email#email.email'});
{
"_id" : ObjectId("54b94759b042bdbf19cb7b97"),
"name" : "Nome da Empresa",
"cnpj" : "123123123",
"email" : "email#email.email",
"password" : "$2a$08$6UvW8Bux3CwUMok8ac12Sehbd.xCHnVUI51ZwhtGKBjkSa6/MrqUu",
"__v" : 0
}
I'm new to mongodb + mongoose, so I know it's a dumb question, but I just can't realize what is wrong... I've also created a findSellerById() function, and it works perfectly.
EDIT 1:
Using Mongoose debug, here's what it's printed:
Mongoose: sellers.findOne({ email: 'email#email.email' }) { fields: undefined }
Mongoose: sellers.findOne({}) { fields: undefined }
As you can see, also tried with no parameters, no success...
I had the same problem, maybe you could try this:
Seller.find({email: seller.email}, function(err, seller){
console.log(seller);
});
This solved mine, hope it will solve yours too !
The callback function passed into findOne takes two parameters (error and doc), so you're treating seller as the error parameter instead of the doc parameter.
So your function should look like this instead:
getSellerByEmail : function(email,next){
var Seller = mongoose.model('Seller');
console.log(inspect(email));
Seller.findOne({'email' : new RegExp(email, 'i')}, function(err, seller){
next(seller);
});
}

Categories

Resources