I am building a query like this
let searchData = request.all()
let products = Product.query().where('product_type', searchData.type).with('singleImage').paginate(1, 20)
if(parseInt(searchData.minPrice) > 0 && parseInt(searchData.maxPrice) > 0) {
products.where("lowerPrice", ">=", searchData.minPrice).where("upperPrice", "<=", searchData.maxPrice)
}
// more conditions and query goes here
It doesn't work because of .paginate(1, 20) and if I remove pagination it works.
You need to execute paginate or fetch after put all your conditions. For example:
let searchData = request.all()
let products = Product.query()
.where('product_type',searchData.type)
.with('singleImage')
// Remove pagination from here
if(parseInt(searchData.minPrice) > 0 && parseInt(searchData.maxPrice) > 0)
{
products.where("lowerPrice", ">=", searchData.minPrice)
.where("upperPrice", "<=", searchData.maxPrice)
}
// Put all your conditions
// Finally execute paginate with await or yield it depends of adonis version (await or yield)
products = await products.paginate(1,20)
Related
With this script I can exclude to insert the same value column in Google Sheet for maximum 100 times.
But I am trying to exclude (with if statement) some values from this script, in particular the date "25/12/2022" and the date "12/01/2012".
How could I proceed?
function onEdit(e) {
var r = e.range;
var s = r.getSheet();
if (s.getName() === 'New Rise 2022' && r.getColumn() === 27) {
var newValue = r.getDisplayValue();
if (newValue == "") return;
var count = s.getRange('AA1:AA').getDisplayValues().filter(([a]) => a === newValue).length;
if (count > 99) {
r.setValue(e.oldValue);
SpreadsheetApp.flush();
SpreadsheetApp.getUi().alert('Questa data è stata già inserita 100 volte');
}
}
}
Update:
function onEdit(e) {
var r = e.range;
var s = r.getSheet();
if (s.getName() === 'New Rise 2022' && r.getColumn() === 27) {
var newValue = r.getDisplayValue();
if (newValue == "") return;
var count = s.getRange('AA1:AA').getDisplayValues().filter(([a]) => a === newValue).length;
if (count > 99 || e.range.getDisplayValue() == "25/12/2012" || e.range.getDisplayValue() == "12/01/2012") {
r.setValue(e.oldValue);
r.setNumberFormat('dd/mm/YYYY');
SpreadsheetApp.flush();
SpreadsheetApp.getUi().alert('Questa data è stata già inserita 100 volte');
}
}
}
How about this?
function onEdit(e) {
const sh = e.range.getSheet();
const x = ["25/12/2022","12/01/2012"];
const idx = x.indexOf(e.value);
if (sh.getName() === 'New Rise 2022' && e.range.columnStart == 27 && e.value && !~idx) {
var count = sh.getRange('AA1:AA' + sh.getLastRow()).getDisplayValues().flat().filter(e => e == e.value).length;
if (count > 99) {
e.range.setValue(e.oldValue);
}
}
}
You can get the newly entered display value and compare it against the "forbidden" values
Therefore, retrieve the latest modified cell with e.range:
...
if (count > 99 || e.range.getDisplayValue() == "25/12/2022" || e.range.getDisplayValue() == "12/01/2012") {
...
}
...
Note:
I understood that what you are interested in is the displayed value (date in this case), but depending on your date formatting the display value will be different from the value you typed in.
If it is the typed in value you are after, you can retrieve it with e.value:
...
console.log("e.value: " + e.value)
console.log("e.range.getDisplayValue(): " + e.range.getDisplayValue())
if (count > 99 || e.value == "25/12/2022" || e.value == "12/01/2012") {
...
}
...
References:
Event Objects
getDisplayValue()
UPDATE:
If you have problems with number formatting you can use the method setNumberFormat().
Modify your code block in the if statement to
r.setValue(e.oldValue);
r.setNumberFormat('dd/mm/YYYY');
I want to make that in a Todo app, only the elements that have the true value are showing in the list. How can I do this?
You can check using where in your stream like this
Stream<List<TodoItem>> getSomeoneItems() {
return FirebaseFirestore.instance.collection('items')
.where('your field name', isEqualTo: true)
.snapshots()
.map((qSnap) =>
qSnap.docs.map((doc) => TodoItem.fromJson(doc.data())).toList());
}
we consider this is your list
List = [
Model(name:"1" , val: true)
Model(name:"2" , val: false)
Model(name:"3" , val: true)
]
and with the below code we can find items with true val
List result = [];
a.forEach((element) {
if(element.val == true){
result.add(element);
}
})
The scan works fine if I provide two or less filter conditions, like this:
FilterExpression: '#locationID = :areaID and #price >= :minPrice'
But if I add a third condition, I get no results:
FilterExpression: '#locationID = :areaID and #price >= :minPrice and #offeringType = :offeringType'
I tried using only #offeringType, the condition is working properly by itself.
Can I have more than two conditions?
Full code:
let params = {
TableName: 'properties',
ExpressionAttributeNames: {
'#locationID': 'locationID',
'#price': 'price',
'#offeringType': 'offeringType',
},
ExpressionAttributeValues: {
':areaID': areaID,
':minPrice': parseInt(minPrice),
':offeringType': offeringType
},
FilterExpression: '#locationID = :areaID and #price >= :minPrice and #offeringType = :offeringType'
}
documentClient.scan(params, (err, data) => {
if (err) {
console.log(err)
reject()
} else {
resolve(data)
}
})
Thanks
The expression was acting weird because #price wasn't a Number in the database. Chaining expressions with AND works fine.
I have some documents in my Couchbase with the following template:
{
"id": 102750,
"status": 5,
"updatedAt": "2014-09-10T10:50:39.297Z",
"points1": 1,
"points2": -3,
"user1": {
"id": 26522,
...
},
"user2": {
"id": 38383,
...
},
....
}
What I want to do is to group the documents on the user and sum the points for each user and then show the top 100 users in the last week. I have been circling around but I haven't come with any solution.
I have started with the following map function:
function (doc, meta) {
if (doc.user1 && doc.user2) {
emit(doc.user1.id, doc.points1);
emit(doc.user2.id, doc.points2);
}
}
and then tried the sum to reduce the results but clearly I was wrong because I wasn't able to sort on the points and I couldn't also include the date parameter
you need to see my exemple I was able to group by date and show the values with reduce. but calculate the sum I did it in my program.
see the response How can I groupBy and change content of the value in couchbase?
I have solved this issue by the help of a server side script.
What I have done is I changed my map function to be like this:
function (doc, meta) {
if (doc.user1 && doc.user2) {
emit(dateToArray(doc.createdAt), { 'userId': doc.user1.id, 'points': doc.points1});
emit(dateToArray(doc.createdAt), { 'userId': doc.user2.id, 'points': doc.points2});
}
}
And in the script I query the view with the desired parameters and then I group and sort them then send the top 100 users.
I am using Node JS so my script is like this: (the results are what I read from couchbase view)
function filterResults(results) {
debug('filtering ' + results.length + ' entries..');
// get the values
var values = _.pluck(results, 'value');
var groupedUsers = {};
// grouping users and sum their points in the games
// groupedUsers will be like the follwoing:
// {
// '443322': 33,
// '667788': 55,
// ...
// }
for (var val in values) {
var userId = values[val].userId;
var points = values[val].points;
if (_.has(groupedUsers, userId)) {
groupedUsers[userId] += points;
}
else
groupedUsers[userId] = points;
}
// changing the groupedUsers to array form so it can be sorted by points:
// [['443322', 33], ['667788', 55], ...]
var topUsers = _.pairs(groupedUsers);
// sort descending
topUsers.sort(function(a, b) {
return b[1] - a[1];
});
debug('Number of users: ' + topUsers.length + '. Returning top 100 users');
return _.first(topUsers, 100);
}
I'm noticing significant code duplication while building my first Meteor project, and I'm wondering if there's a way to DRY it up.
My database model has stores, each of which have a number of products, and a field with the amount currently in inventory.
var store_id = Store.insert({name: 'Store 1', max_items: 50});
var p1 = Product.insert({name: 'General', store_id: store_id, item_count: 20});
var p2 = Product.insert({name: 'Special', store_id: store_id, item_count: 10});
I have a template to display a store, and statistics on how many products and items it has.
<template name="store">
<div class="store">
<b>{{name}}</b>
<p>Current items: {{current_items}}</p>
<p>Maximum # of items allowed in inventory: {{max_items}}</p>
<p>% Full: {{percent_full}}%</p>
</div>
</template>
Calculating the number of current items seems fairly straightforward, I pull all the products, sum the item counts (using d3), return the result.
Template.store.current_items = function () {
var store_id = this._id;
var items = Product.find({store_id: store_id}).fetch();
if ( items.length > 0 ) {
var item_cnt = d3.sum(_.pluck(items, 'item_count'));
return item_cnt;
}
else {
return 'N/A';
}
};
To calculate a percentage comparing the total # of allowed items, and the current items, it seems like I have to reduplicate everything. Is there a better way to do this?
Template.store.percent_full = function () {
var store_id = this._id;
var items = Product.find({store_id: store_id}).fetch();
if ( items.length > 0 ) {
var item_cnt = d3.sum(_.pluck(items, 'item_count'));
return item_cnt / max_items * 100;
}
else {
return 'N/A';
}
};
Extract the duplicated logic to a separate function and just call it appropriately from different helpers. This is not really different from DRYing any other JS code.