Search data in mongodb according to field values - arrays

I am using mongodb and node.js. In my database i have 6 fields that is
bid
color (Array)
size (Array)
cat_id
sub_cat_id
All is working fine. Now i want to add filter in my code. In filter area i have add this all fields. user select multiple colors and sizes so it will come in Array format but most of the time user will not select color option or size option at that time field values comes blank so my filter will not take any result from database. so i want to remove color or size field if value is empty during search. I have tried below code but its not working.how i do this.
var catId = new Array();
var sort = saveFilterSort.sort;
var filter = req.body;
if(req.body.catId){
catId.push("category_id:"+req.body.catId);
}
if(req.body.subcatid){
catId.push("sub_category_id:"+req.body.subcatid);
}
if(req.body.minprice){
catId.push("price:{$gt:"+req.body.minprice+"}");
}
if(req.body.maxprice){
catId.push("price:{$lt:"+req.body.maxprice+"}");
}
if(req.body.color){
catId.push("color:{$in:"+req.body.color+"}");
}
if(req.body.size){
catId.push("attribute:{$in:"+req.body.size+"}");
}
var finalCat = catId.join(',');
console.log(finalCat);
console.log(catId);
if((filter) && (sort)){
Product.find(
{
brand_id:bid, finalCat
},
function(error,fetchallFeatProds)
{
console.log('#######################');
console.log(fetchallFeatProds);
console.log('#######################');
callback(error,fetchallFeatProds);
}).sort( {_id:-1,price:-1} );
This code is not working. Please help me.

Mongoose find prototype handle json and not string
var query = {brand_id:bid};
var sort = saveFilterSort.sort;
var filter = req.body;
if(req.body.catId){
query.category_id = req.body.catId;
}
if(req.body.subcatid){
query.sub_category_id = req.body.subcatid;
}
if(req.body.minprice){
query.price = {$gt:req.body.minprice};
}
if(req.body.maxprice){
query.price = {$lt:req.body.maxprice};
}
if(req.body.color){
query.color = {$in:req.body.color};
}
if(req.body.size){
query.attribute = {$in:req.body.size};
}
if((filter) && (sort)){
Product.find(query, ...

Related

Azure search API - search filter syntax

I'm using the azure search api trying to filter by a certain field value: businesstype = store. It always returns 3 stores, even though I should have thousands. I can't tell for sure what's inside the index. In the Azure search web portal I type businessType eq 'store' and it gives me two stores, then starts returning businesstype = restaurant. Not sure what is going on. We have other implementations in other projects where filters are working. Here's code that I'm executing as it is invoked by using ASP.NET Web API
var indexClient = new SearchIndexClient(GlobalSettings.SearchServiceName, $"businesses{GlobalSettings.Environment}", new SearchCredentials(GlobalSettings.SearchServiceAdminApiKey));
if (latitude == null && longitude == null)
{
//chicago
latitude = 41.8333925;
longitude = -88.0121478;
}
// get all attributes and camel case them
var attributes = typeof(BusinessSearchItem).GetProperties().Select(x => char.ToLowerInvariant(x.Name[0]) + x.Name.Substring(1)).ToList();
var parameters = new SearchParameters
{
Select = attributes,
QueryType = QueryType.Full,
Top = take,
Skip = skip,
IncludeTotalResultCount = true,
OrderBy = new List<string>() { $"geo.distance(location, geography'POINT({longitude} {latitude})')" }
};
// filters
string filter = "";
if (!string.IsNullOrEmpty(businessType))
{
switch (businessType.ToLower())
{
case "restaurant":
filter += "businessType eq 'Restaurant'";
break;
case "store":
filter += "businessType eq 'Store'";
break;
}// end switch on business type
}
parameters.Filter = filter;
try
{
// run the search
var results = indexClient.Documents.Search<BusinessSearchItem>(q, parameters);
Logger.Log.Info($"Search conducted. Query: {q} Business Type: {businessType} Lat: {latitude} Long: {longitude} User: {username}");
var businessDTOs = results.Results.Select(x => new BusinessDTO
{
.........
).ToList()
}).ToList();
the model BusinessSearchItem has a field BusinessType of string that has the attribute searchable. The skip is 0 and take 40.
The problem wasn't the search at all, it was that the data was not in the index

cakephp looping only save first row of data, others row not saving

Looping to save each column field picture1pic6:
Please help, i using cake php version 2.0, try to do looping to save each column, but only the first row data save, the data should be save like attached picture1.Hope someone can help, i tried to figure out 2 weeks. V_COUNT i hardcode the number to 23.
if($this->IPI->save($this->request->data))
{
$table_name = 'IPI_V';
$this->IPI->setSource($table_name);
for($i=1;$i<=$this->request->data['IPI']['V_COUNT'];$i++)
{
if($i<10){$i = '0'. $i;}
if(($this->request->data['IPI']['Quantity'.$i])!=NULL)
{
$this->request->data['IPI']['Type_Defect'] = $this->request->data['IPI']['Type_Defect'.$i];
$this->request->data['IPI']['CAT'] = $this->request->data['IPI']['CAT'.$i];
$this->request->data['IPI']['Defect'] = $this->request->data['IPI']['Defect'.$i];
$this->request->data['IPI']['Quantity'] = $this->request->data['IPI']['Quantity'.$i];
$this->IPI->create();
$this->IPI->save($this->request->data);
}
}
try this
if($this->IPI->save($this->request->data))
{
$table_name = 'IPI_V';
for($i=1;$i<=$this->request->data['IPI']['V_COUNT'];$i++)
{
$data = array();
if($i<10){$i = '0'. $i;}
if(($this->request->data['IPI']['Quantity'.$i])!=NULL)
{
$data['IPI']['Type_Defect'] = $this->request->data['IPI']['Type_Defect'.$i];
$data['IPI']['CAT'] = $this->request->data['IPI']['CAT'.$i];
$data['IPI']['Defect'] = $this->request->data['IPI']['Defect'.$i];
$data['IPI']['Quantity'] = $this->request->data['IPI']['Quantity'.$i];
$this->IPI->setSource($table_name);
$this->IPI->create();
$this->IPI->save($data);
}
}

AS3 Separating Arrays for different items

I have a function that creates a new value inside an associative array.
var array:Array = new Array(new Array());
var i : int = 0;
function personVelgLand(evt:MouseEvent)
{
for(i = 0; i < personListe.dataProvider.length; i++)
{
if(txtPersonVelg.text == personListe.dataProvider.getItemAt(i).label)
{
personListe.dataProvider.getItemAt(i).reise = array;
personListe.dataProvider.getItemAt(i).reise.push(landListe.selectedItem.land);
}
}
}
What happens is that the 'array' array which becomes 'personListe.dataProvider.getItemAt(i).reise' applies to every item in the list. I want it so that each time the function runs that the .reise only applies to the item chosen and not all of them.
EDIT:
I did this:
personListe.dataProvider.getItemAt(i).reise = new Array(array);
And now they are not the same but now each item in the list can not have multiple .reise values...
EDIT 2: dataProvider is nothing it would work just as fine without it. .reise is created in the function I originally posted it creates .reise in the object getItemAt(i).
personListe is a list which the users add their own items to by the use of a input textfield. It is given by this function:
function regPerson(evt:MouseEvent)
{
regPersoner.push(txtRegPerson.text);
personListe.addItem({label:regPersoner});
regPersoner = new Array();
txtRegPerson.text = "";
}
EDIT 3 : The user can register names which turn in to labels in a list. There is also list with 3 countries, Spain, Portugal and England. The user can then register a country to a person they select. Thats when I want to create the .reise inside the "name" items in the first list which contains the countries they have selected. I want every name to be able to select multiple countries which then will be created in the element .reise inside the item that holds their name. This would be easy if I could use strings. But later I plan to have the user type in a country and then something that would show every user that have selected that country. That is why the countries need to be stored as arrays inside the "name" items..
You should first create a class for the User data that you are modelling. You already know all the properties.
The user can register names
The user can then register a country to a person they select.
able to select multiple countries
Such a class could look like this:
package
{
public class User
{
private var _name:String;
private var _countries:Array;
public function User(name:String)
{
_name = name;
_countries = [];
}
public function get name():String
{
return _name;
}
public function get countries():Array
{
return _countries;
}
public function set countries(value:Array):void
{
_countries = value;
}
}
}
Now create a DataProvider, fill it with objects of that class and use it for the list as described here:
import fl.controls.List;
import fl.data.DataProvider;
var users:List = new List();
users.dataProvider = new DataProvider([
new User("David"),
new User("Colleen"),
new User("Sharon"),
new User("Ronnie"),
new User("James")]);
addChild(users);
users.move(150, 150);
In order to get a label from a User object, define a labelFunction
import fl.controls.List;
import fl.data.DataProvider;
var users:List = new List();
users.labelFunction = userLabelFunction;
function userLabelFunction(item:Object):String
{
return item.name;
}
users.dataProvider = new DataProvider([
new User("David"),
new User("Colleen"),
new User("Sharon"),
new User("Ronnie"),
new User("James")]);
addChild(users);
users.move(150,150);
This way you do not have to add a label property that you don't want in your class.
Selecting a name means selecting a user. The list of countries associated to the name should show up in a second List.
The DataProvider of that List remains constant, a list of all the available countries.
import fl.controls.List;
import fl.data.DataProvider;
// list of users
var users:List = new List();
addChild(users);
users.move(150,150);
users.labelFunction = userLabelFunction;
function userLabelFunction(item:Object):String
{
return item.name;
}
users.dataProvider = new DataProvider([
new User("David"),
new User("Colleen"),
new User("Sharon"),
new User("Ronnie"),
new User("James")]);
// lsit of countries
var countries:List = new List();
addChild(countries);
countries.move(550,150); // adjut position as desired
countries.dataProvider = new DataProvider([
{label:"a"},
{label:"b"},
{label:"c"},
{label:"d"},
{label:"e"},
{label:"f"}]);
Now all you have to do is to wire it all up. If a user is selected, select his countries in the countries list. If a country is selected, add that to the currently selected users list of countries. That could look somethign like this:
users.addEventLsitener(Event.CHANGE, onUserSelected);
function onUserSelected(e:Event):void
{
countries.selectedItems = users.selectedItem.countries;
}
countries.addEventLsitener(Event.CHANGE, onCountrySelected);
function onCountrySelected(e:Event):void
{
users.selectedItem.countries = countries.selectedItems;
}
The full code could look like this. I did not test this, but you get the idea.
// list of users
var users:List = new List();
addChild(users);
users.move(150,150);
users.labelFunction = userLabelFunction;
function userLabelFunction(item:Object):String
{
return item.name;
}
users.dataProvider = new DataProvider([
new User("David"),
new User("Colleen"),
new User("Sharon"),
new User("Ronnie"),
new User("James")]);
// list of countries
var countries:List = new List();
addChild(countries);
countries.move(550,150); // adjut position as desired
countries.dataProvider = new DataProvider([
{label:"a"},
{label:"b"},
{label:"c"},
{label:"d"},
{label:"e"},
{label:"f"}]);
// events
users.addEventLsitener(Event.CHANGE, onUserSelected);
function onUserSelected(e:Event):void
{
countries.selectedItems = users.selectedItem.countries;
}
countries.addEventLsitener(Event.CHANGE, onCountrySelected);
function onCountrySelected(e:Event):void
{
users.selectedItem.countries = countries.selectedItems;
}
From what I understand this seems to work except for the fact that the names are already provided when the program starts. What I want is that the user adds the name themselves while the program is running.
You can add new items with the methods provided by the DataProvider class, like addItem() for example. Just add new User objects.

Get back #html.dropdownlist ID value for database insert / update in Webmatrix

I have build some dropdown lists using the LINK to Objects method and #html.dropdownlist Webmatrix helper. This works fine.
I want to know how to pass / store the selected value in my database table.
Build of items list in code section
var titlesData = db.Query("SELECT TitleId, Name FROM Titles ORDER BY Name");
titlesListItems = titlesData.Select(i => new SelectListItem {
Value = i.TitleId.ToString(),
Text = i.Name,
Selected = i.TitleId == providerData.TitleId ? true : false
});
HTML markup section:
#Html.DropDownList("titlesCombo","-- Veuillez sélectionner -- ",titlesListItems)
Database update command (see the ???):
db.Execute("UPDATE Providers SET TitleId=#0 WHERE ProviderId=#1",???,providerId)
The method I used for now is to create another variable:
var titleId = "";
if (!IsPost) {
titleId = providerData.TitleId.ToString(); //providerData stores the SQL query result
}
if (IsPost) {
var titleId = Request.Form[TitleID]
db.Execute("UPDATE Providers SET TitleId=#0 WHERE ProviderId=#1",titleId,providerId)
}
Unfortunately, data doesn't get updated
From what I can see, you haven't referenced rightly the DropDownList helper in your code.
Try with the following code:
var titleId = "";
if (!IsPost) {
titleId = providerData.TitleId.ToString();
}
if (IsPost) {
titleId = Request.Form["titlesCombo"];
db.Execute("UPDATE Providers SET TitleId=#0 WHERE ProviderId=#1",titleId,providerId);
}

url sharepoint list camlquery

I'm trying to collect my url and the description of the url stored in a column of a list from sharepoint and i don't know how to collect the URL value.
This is my code :
var queryResultSaleListItems = clientContext.LoadQuery(listData);
clientContext.ExecuteQuery();
//Read the Data into the Object
var TipsList = from Tips in queryResultSaleListItems
select Tips;
ObservableCollection<Tips> colTips = new ObservableCollection<Tips>();
//Read Every List Item and Display Data into the DataGrid
foreach (SPSClient.ListItem item in TipsList)
{
var tips = new Tips();
tips.TitleTip = item.FieldValues.Values.ElementAt(1).ToString();
tips.App = item.FieldValues.Values.ElementAt(4).ToString();
//should collect the url
tips.URL = item.FieldValues.Values.ElementAt(5).ToString();
//should collect the description of the url
tips.URLdesc = item.FieldValues.Values.ElementAt(5).ToString();
colTips.Add(tips);
}
ListboxTips.DataContext = colTips;
In my expression its >
((Microsoft.SharePoint.Client.FieldUrlValue)(item.FieldValues.Values.ElementAt(5))).Url
((Microsoft.SharePoint.Client.FieldUrlValue)(item.FieldValues.Values.ElementAt(5))).Description
Thanks for your help,
Use FieldUrlValue for getting hyperlink field in Client Object Model.
Use Following Code:
string server = "siteURL";
var ctx = new ClientContext(server);
var web = ctx.Web;
var list = web.Lists.GetByTitle("CustomList");
var listItemCollection = list.GetItems(CamlQuery.CreateAllItemsQuery());
ctx.Load(listItemCollection);
ctx.ExecuteQuery();
foreach (Microsoft.SharePoint.Client.ListItem listItem in listItemCollection)
{
string acturlURL = ((FieldUrlValue)(listItem["URL"])).Url.ToString(); // get the Hyperlink field URL value
string actdesc = ((FieldUrlValue)(listItem["URL"])).Description.ToString(); // get the Hyperlink field Description value
}

Resources