Sequelize query to select match or partially match name - javascript

I need your help. I am working on a web server with node.js and reactJS. I want to make a page for the Admin called "Users" to search for the users in the SQL database. I wrote a code that create two options to search Users by "Name" or "Country"
this is the code:
UserSearch: {
fields : {
firstname: {value:'', type:'text', label:"Name", placeholder:'type name', bluredBefore:false, validators:['non'], errorReport:[]},
country: {value:'-1', type:'select', label:"Country", placeholder:'select country', staticDataSource:'countries', bluredBefore:false, validators:['non'], errorReport:[]},
},
errorReport:false,
isWaiting : false,
queryTarget: 'userFind',
queryView: 'UserSearchGrid',
queryViewFields: 'userId, firstname, lastname ',
formCols:3,
notification: '',
},
UserSearchGrid: {searchForm:'UserSearch',
viewFields: ['userId','firstname','lastname'],
dataSource:[], count:0, offset:0, limit:10},
In the query file I wrote this code:
var where = {userId:userId,};
if (typeof args.firstname !== 'undefined' && args.firstname !== '')
where['firstname'] = args.firstname;
if (typeof args.country !== 'undefined' && args.country !== '-1')
where['country'] = args.country;
items = await UserProfile.findAndCountAll({
where: where, })
Now these two pieces of codes create a text-box "Name" and a drop-down menu "Country" and the Admin have to select the exact username and the correct country to get a result.
I need a sequelize query that let the Admin to enter the name (either first or last name) OR the country and get the result with any matching name or partially match or with the matching country.
Additional: I don't know if it possible, I want the to results to appear during that the admin is writing the name ( matching every typed letter and show the results ) . Thanks in advance for anyone can help.

Solved:
I Edited my if statement to be like this :
var where = {};
if (typeof args.firstname !== 'undefined' && args.firstname !== '')
// where['firstname'] = args.firstname;
where['$or']={firstname:{$like: `%${args.firstname}%`},lastname:{$like: `%${args.firstname}%`}};
items = await UserProfile.findAndCountAll({
where: where , })
(where) is an object that contains the clause (or), it do Select from database firstname or lastname containing (args.firstname) -that had been entered by the Admin-
Ex: I want to search for the user "John" in the database, if I typed "Jo" it will get the result with all users that have "John" as their firstname or lastname from database as they containing "Jo" in their name.

Related

select query in MySQL NodeJS

I am making search route for property table where user can enter city, state, street_address , minamount , max_amount to search for different properties. My problem is if user only enter one or two fileds search should be filter by those field only. and if user does not enter any parameters, it should show every property.
const sqlQuery = `SELECT * FROM property WHERE state = ? AND city = ? AND street_address = ? AND min_amount >= ? AND max_amount <= ?; `
const values = [req.body.state, req.body.city, req.body.street_address ,req.body.min_amount,req.body.max_amount];
let data = [];
db.query (sqlQuery, values, function (err, results, fields) {
if (err) {
console.log(err)
}
if (results.length >= 1) {
}
You need to construct your sqlQuery manually by checking the existence of each parameter and appending a corresponding WHERE clause individually for each parameter, if this parameter exists.

Why does select with case and union return an empty array with node and sqlite

I've got a problem with a sqlite query on node. The query with SqliteStudio is working, but with Node.js I get an empty array.
Here's the query:
const query =`
SELECT 'telephone' AS type,telephone AS data,CASE
WHEN telephone = (
SELECT data FROM customers_verified_contact_infos
WHERE type='telephone' AND data=j.telephone AND customer_id = ?
) THEN 'true'
ELSE 'false'
END AS verified
FROM customers j WHERE customer_id = ? AND telephone IS NOT NULL
UNION
SELECT 'email' AS type,email AS data,CASE
WHEN email = (
SELECT data FROM customers_verified_contact_infos
WHERE type='email' AND data=email AND customer_id = ?
) THEN 'true'
ELSE 'false'
END AS verified
FROM customers WHERE customer_id = ? AND email IS NOT NULL
UNION
SELECT 'fax' AS type,fax AS data,CASE
WHEN fax = (
SELECT data FROM customers_verified_contact_infos
WHERE type='fax' AND data=fax AND customer_id = ?
) THEN 'true'
ELSE 'false'
END AS verified
FROM customers WHERE customer_id = ? AND fax IS NOT NULL
UNION
SELECT type,data, 'true' AS verified
FROM customers_verified_contact_infos WHERE customer_id = ?
`;
I request two tables:
customers, with some customer information
customers_verified_contact_infos, with list contact information verified
Contact information can be in both or just one table.
The result is a list of rows with data, the type of data, and if it's been verified or not.
Now, the Node.js request:
db.all(query,[customer_id], (err, data) => {
console.log(data);
});
The data is an empty array and err = null.
With SqliteStudio, with the same query and customer, I get:
I tried SELECT by SELECT, and with case I didn't get a result. I don't find anything on internet which can help me.
If someone can help or give me advice, I'd appreciate it.
Thanks
The query has 7 ? placeholders, but the array [customer_id] only has one element. You need to repeat it for every placeholder.
db.all(query, Array(7).fill(customer_id), (err, data) => {
console.log(data);
});

How do i prevent creating the same user with the same info?

How do I check if the user already created the same LRN ?
and when I press the save button twice it creates two user with the same info
how do I prevent it ?
jQuery('#save_voter').submit(function(e){
e.preventDefault();
var FirstName = jQuery('.FirstName').val();
var LastName = jQuery('.LastName').val();
var Section = jQuery('.Section').val();
var Year = jQuery('.Year').val();
var LRN = jQuery('.LRN').val();
var Password = jQuery('.Password').val();
e.preventDefault();
if (FirstName && LastName && Section && Year && LRN && Password){
var formData = jQuery(this).serialize();
jQuery.ajax({
type: 'POST',
url: 'save_student.php',
data: formData,
success: function(msg){
showNotification({
message: "Student Successfully Added",
type: "success",
autoClose: true,
duration: 5
});
By creating a unique constraint on the username field. It seems that in your case the LRN field is the username field. Make it unique by
ALTER TABLE users ADD UNIQUE INDEX uname on users (LRN);
Then you can try something like this to tell the end user that the username is duplicated.
try{
$res =$connection->query(your user insert);
}catch(Exception $e){
echo 'Sorry already exists';
}
You need to do 3 steps :
Check manually First Name and Last Name already exists or not in PHP file
In resultset contains more than 0 records, then return false which means record already exists.
In JQuery, if its getting false, then show an error message that record already exists.
Further, as #kongkang said in comments that the field LRN is as username.
then still you need to do 3 steps :
Make that field as unique in database table
Add if condition on insertion query (PHP File) that if return false it means record already exists
in Jquery, if returning value is false, then show error message.
Add a unique index to your database for a unique field.I hope LRN is there for you. Then
MYSQL:
ALTER TABLE users ADD UNIQUE (LRN)
SQL SERVER:
ALTER TABLE [users] ADD CONSTRAINT UC_LRN UNIQUE ([LRN]);
When you try to insert duplicate LRN database error will come automatically for Codeigniter. Without it you have to check manually.

CRM: Javascript to Set Multiple Email Addresses when Replying to an Email

On CRM 2013 I'm trying to insert multiple participants into the email "to" field when users click on "Reply All". However I need to remove certain email addresses from the To line. So I created an array to loop and get all the email addresses except the one that needs to be removed.
However the problem here is that it only works if there is only one participant left after removing the unwanted participants. If there are two or more participants the script will not populate any participants at all.
Is there a way to populate multiple email participants? Or is there a better approach than what I'm trying to do here?
Here's my code:
var toParty = Xrm.Page.getAttribute("to").getValue();
var partyListArray = new Array();
for (var indxAttendees = 0; indxAttendees < toParty.length; indxAttendees++) {
// using oData to get participant email address
var email = getParticipantEmail(
toParty[indxAttendees].entityType,
toParty[indxAttendees].id
);
if (email != "test#test.com") {
partyListArray[indxAttendees] = new Object();
partyListArray[indxAttendees].id = toParty[indxAttendees].id;
partyListArray[indxAttendees].name = toParty[indxAttendees].name;
partyListArray[indxAttendees].entityType = toParty[indxAttendees].entityType;
}
}
Xrm.Page.getAttribute("to").setValue(null);
Xrm.Page.getAttribute("to").setValue(partyListArray);
Instead of creating a whole new array, you can delete what you want from the array itself. Try this:
var emails = [{email: "add1#domain.com"}, {email: "add2#domain.com"}, {email: "address#toBe.Removed"}, {email: "add3#domain.com"}, {email: "add4#domain.com"}];
var removeIndex = emails.map(function(item) { return item.email; }).indexOf("address#toBe.Removed");
removeIndex > -1 && emails.splice(removeIndex, 1);

Using ternary operator to conditionally set value of a field

I have an object, and I want to set one of the fields to the return of querying the database using the value of another field in the object. The approach below returns null, as Im sure it's not right, but I can't figure out the best way to do this.
shared_user_email should be blank if shared_user is empty, but it should represent the return of a database query if shared_user is populated.
I know that javascript variables are hoisted to the top of the application at runtime, but I seem to be falling victim to order of operations here.
var newList = {
title: $(ev.target).find('[name=title]').val(),
description: $(ev.target).find('[name=description]').val(),
dateCreated: today.toDateString(),
owner: Meteor.userId(),
owner_email: Meteor.user().emails[0].address,
shared_user: $(ev.target).find('[name=shared_user]').val(),
shared_user_email: shared_user_email_field
}
var shared_user_email_field = (newList.shared_user != '') ? Meteor.users.find({_id: $(ev.target).find('[name=shared_user]')
.val()}).fetch()[0].emails[0].address : '';
EDIT
here is the server side method that is invoked right after the object is created, which passes newList to the server:
Meteor.call('addList', newList, function(err, list){
console.log(shared_user_email_field);
return list;
});
var newList = {
title: $(ev.target).find('[name=title]').val(),
description: $(ev.target).find('[name=description]').val(),
dateCreated: today.toDateString(),
owner: Meteor.userId(),
owner_email: Meteor.user().emails[0].address,
shared_user: $(ev.target).find('[name=shared_user]').val(),
shared_user_email: ''
}
newList.shared_user_email = (newList.shared_user != '') ? Meteor.users.find({_id: $(ev.target).find('[name=shared_user]')
.val()}).fetch()[0].emails[0].address : '';

Categories

Resources