I'm trying a like query in name & surname columns with a dynamic input, using ES6 string interpolation.
This is my code:
User.findAll({
where: {
[Op.or] : [
{
nombre: {
[Op.iLike] : `%${name}%`
}
},
{
apellido: {
[Op.iLike] : `%${name}%`
}
}
]
},
attributes:userAttr,
})
Sequelize adds automatically N\' at beginning in each dynamic variable, and throws the following SQL statement:
'SELECT [id] AS [id], [mail] AS [email], [nombre] AS [name], [apellido] AS [surname], [nro_celular] AS [cellphone], [tipo] AS [type], [id_usuario_estado_actual] AS [userCurrentStatusID], [push_token] AS [pushToken], [push_user_id] AS [pushUserID], [documento] AS [document], [tipo_documento] AS [documentType], [fecha_creacion] AS [creationDate], [id_ciudad] AS [cityID], [id_empresa] AS [companyID], [default_payment] AS [paymentDefault] FROM [dbo].[usuario] AS [user] WHERE ([user].[nombre] ILIKE N\'%Axel Candia%\' OR [user].[apellido] ILIKE N\'%Axel Candia%\');'
Which throws the following error
UnhandledPromiseRejectionWarning: SequelizeDatabaseError: Incorrect syntax near 'ILIKE'.
I've tried the following suggestions, unsuccessfully:
[Op.iLike] : '%'+name+'%'
$iLike : '%'+name+'%'
[Op.iLike] : ['%'+name+'%']
Any other suggestion?
SOLVED 6/28/2018 11:03 AM
The error wasn't focused in N\' added by Sequelize,
[Op.iLike] it's only for PG (Postgres) Database, not mine (SQL Server).
Instead, [Op.like] works as charm! However, I should code a solution for insensitive case in dynamic variables.
Related
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.
select reservation_datetime
from LectureReservation
Inner Join Lecture
On LectureReservation.lecture_id = Lecture.id
Where Lecture.mentor_id = 1
This is my query and I want to change it to sequelize like
if (req.params.id) {
LectureReservation
.findAll({
include: [{
model: Lecture,
where: { mentor_id: req.params.id },
}],
attributes: ['reservation_datetime'],
where: {
lecture_id: Lecture.id,
},
this.. I tried it so hard but can't find solution and my postman keep showing me
"name": "SequelizeEagerLoadingError"
this err..
plz help me to translate query to sequelize..!
Sequelize will do _outer join without required = true.
The errors you have received usually is from association problem.
Try set logging :console.log and check the raw query.
I am trying to order by the count of the associated model, and have been getting the following error from Sequelize
Cannot read property '_modelAttribute' of undefined
I have following code:
db.user.belongsToMany(db.user, {
as: "User",
through: "UserFollowers",
foreignKey: "user_id"
});
db.user.belongsToMany(db.user, {
as: "Follower",
through: "UserFollowers",
foreignKey: "follower_id"
});
and
User.findAll({
attributes:["username",db.sequelize.literal('(SELECT COUNT(*) FROM "public"."Users","public"."UserFollowers" WHERE "Users".user_id = "UserFollowers".user_id GROUP BY "Users".user_id)'),'followercount'],
include:[{model:User,as:'Follower'}],
order:[{ model: User, as: 'Follower' }[db.sequelize.literal('followercount')],'DESC']
}).then(users => {
res.json(users)
})
I appreciate any help!
From glancing at the code, the issue seems to be on the ordering clause.
Change it to:
order: [[{ model: User, as: 'Follower' }, 'followercount', 'DESC']]
If that doesn't cut it, try logging the outcome of the query by adding logging: console.log. That should help you identify what part is failing by analyzing the sql query.
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
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);
});
}