Mongo Aggregation: Using new Date() as in input to form a AggregationExpression - spring-data-mongodb

does anybody know how to achieve this statement with spring mongo projection:
timed: {
$divide: [{ $subtract: [ new Date(), "$created" ] }, 7200000]
}
Something like this doesn't work for me:
ArithmeticOperators.Subtract updated = valueOf("new Date()").subtract("created");
because valueOf expects a field reference or an AggregationExpression

You can try below stage. new Date() in shell query is javascript date function. You have to use the BasicDBObject to wrap that expression inside the AggregationExpression.
ArithmeticOperators.Divide updated = ArithmeticOperators.Divide.valueOf(aggregationOperationContext -> new BasicDBObject("$subtract", Arrays.asList(new Date(), "$created"))).divideBy(7200000);
AggregationOperation project = Aggregation.project().and(updated).as("timed");
Aggregation agg = newAggregation(project);
I was not able to find a way to pass something like two date arguments
valueOf("created").subtract(new Date())

I meet the same problem as you . I fix it by the following code:
String pattern = "yyyy-MM-dd HH:mm:ss";
String dateNow = DateFormatUtil.getDateNow();
DateOperators.DateFromString date = DateOperators.dateFromString(dateNow);
date.withFormat(pattern);
ArithmeticOperators.Subtract subtract = ArithmeticOperators.Subtract.valueOf("deadline").subtract(date);
ArithmeticOperators.Divide divide = ArithmeticOperators.Divide.valueOf(subtract).divideBy(3600000);
subtract() method may need a param like AggregationExpression , and the DateOperators.dateFromString is the implement.
I hope this can be helpful. 0-0

Related

Mongoose querying the array... changing the elements of the array

I am trying to remove all the elements from the array in the MongoDB database, then I insert all the new array elements.
My Model is:
const mongoose = require('mongoose');
var schema = new mongoose.Schema({
email : {
type : String
},
password : {
type : String
},
stocks : {
type : [String]
}
}, {versionKey:false}, {_id: false});
module.exports = final = mongoose.model('users', schema);
My stocks array will then have some values. I am trying to remove those values using the following command:
I read at somewhere in Stack Overflow that to empty your array you can do many things but a set is the fastest way to do this. Please let me know if you know any other way which is better than this.
final
.findOneAndUpdate({email:"abcd#gmail.com"}, {$set:{stocks:[]}})
.then(()=>console.log("Data removed."))
.catch(err=>console.log(err));
Once data is removed it means the array will get emptied. Then I assign the whole set of the new array from my local variable like this:
const newData = {
stocks : ["abcd", "wxyz"]
};
Now I am trying to assign this new array to my database using this command:
final
.findOneAndUpdate({email:"abcd#gmail.com"}, {$set:{stocks:newData.stocks}});
It is emptying the array successfully, but when I am assigning new array it is not working and shows an empty array. Can anyone assist me with this, please?
Try with
final.findOneAndUpdate({email:"abcd#gmail.com"}, {$set:{stocks:newData.stocks}}, {new: true})
.then((doc)=>console.log(doc))
.catch(err=>console.log(err));
If you don't use a callback the query is not executed.
The query executes if callback is passed else a Query object is returned.
Mongoose documentation

How to make a command time counter

My question is: how can I make a command clock (when you execute !count and after 4 minutes you type !time and it says 4 minutes!) in discord.js
const Discord = require('discord.js');
exports.run = (client, message) => {
var af = 0;
a = setInterval(function(){
console.log("Hi");
af = af+1;
if(af == 25){
clearInterval(a);
}
console.log(af);
}, 60000);
};
exports.help = {
name: 'time',
description: 'time?',
usage: 'time'
};
I would do it like this: when you execute !count you save the server time, when you execute !time you send back the difference between those two dates.
Pseudo-code:
var date;
if (command == 'count') {
date = new Date();
message.reply("Done");
}
if (command == 'time') {
let result = require('pretty-ms')(date ? (new Date() - date) : 0);
message.reply(result);
}
I'm using the pretty-ms npm package to format milliseconds: docs & live demo.
When someone calls !count, store the current Date somewhere. new Date() - date will give you the difference between the current time and the time you stored, in milliseconds.
Please note that if the commands are in different files, as it seems by the code you posted, you'll need to store the date in a location accessible to both files: one of the solutions is to store the date as a global variable.
// by '...' I mean that you can put it wherever you want in the global object
global['...'].date = new Date():
new Date() - global['...'].date
Edit: Date class explanation
When you create a new Date, it saves the time at the moment you create it. It's like saying "!count was executed at 04:20". When you want to check how much time has passed, you need to calculate the first date minus the current date: "!count was executed at 04:20. Now it's 05:40, so the difference is 05:40 - 04:20 = 01:20: it's 1 hour and 20 minutes since you first executed !count". That translates to new Date() - past_date = time_passed.
Since dates are stored in milliseconds that difference is in milliseconds: if you want to make it more readable, you can format it by using a function as the 'pretty-ms' package, or similar ones.
The key concept is:
When !count is called, you save a new Date() to lock that point in time
When !time is called, you get the difference by doing new Date() - past_date

How to pass datetime parameter to HTTP GET message

I want to pass two Datetime Parameter from form to WEB API from Angular JS but could not make it work. However I am able to pass only date without time to WEB API Method.
My form DateTime controls looks like below:-
Now I want to pass Datetime like below from Angular JS:-
Angular JS Call
var startTime = $filter('date')($scope.md_invstarttime, "HH:mm");
startTime = startTime.split(':');
var invStartDate = new Date($scope.md_invstart);
invStartDate.setHours(startTime[0]);
invStartDate.setMinutes(startTime[1]);
var invBookDate = $filter('date')(invStartDate, "yyyy-MM-ddTHH:mm:ss.000")
var endTime = $filter('date')($scope.md_invendtime, "HH:mm");
endTime = endTime.split(':');
var invEndDate = new Date($scope.md_invend);
invEndDate.setHours(endTime[0]);
invEndDate.setMinutes(endTime[1]);
var invBookEndDate = $filter('date')(invEndDate, "yyyy-MM-ddTHH:mm:ss.000")
MetadataOrgFactory.getTriIdApiCall('checkinvavail', invBookDate, invBookEndDate, $scope.md_invid,
function (dataSuccess) {
}, function (dataError) {
});
Controller Method
[Authorize]
[Route("api/checkinvavail/{invstarttime}/{invendtime}/{invid}")]
[HttpGet]
public bool GetInvAvailability(DateTime invstarttime, DateTime invendtime,Guid invid)
{
InventoryBLL checkInv = new InventoryBLL();
bool isAvailable = checkInv.IsAvailable(invstarttime, invendtime,invid)
return isAvailable;
}
I have searched many articles but none could solve my problem and hence this post. It would be really helpful if any one post the exact solution to this problem.
Convert your date object into timestamp by var timestamp = datevar * 1 then pass the timestamp instead. Then in the backend convert the timestamp back to date object.
Instead
var invBookEndDate = $filter('date')(invEndDate, "yyyy-MM-ddTHH:mm:ss.000")
at Front end convert it to timestamp.
invBookEndDate = invEndDate.getTime()
At the backend,convert it back to Date object with appropriate timezone you want.

Convert date format from object containing dates in AngularJS

How to convert above all the date into YYYY-MM-DD format? I have used this way but it's not working.
$scope.dateDatas = [0:"29-09-2016", 1:"30-09-2016",2:"01-10-2016",3:"02-10-2016",4:"03-10-2016"]
angular.forEach ($scope.dateDatas,
function (value) {
var d = $filter('date')(value, 'yyyy-mm-dd');
console.log(d);
});
How about this:
$scope.dateDatas = ["29-09-2016", "30-09-2016", "01-10-2016", "02-10-2016", "03-10-2016"];
$scope.result = [];
angular.forEach ($scope.dateDatas, function (value) {
var splitValue = value.split("-");
var date = new Date(splitValue[2], splitValue[1] - 1, splitValue[0]);
var res = $filter('date')(date, 'yyyy-MM-dd');
$scope.result.push(res);
console.log(res);
});
Here are the issues:
On the first line, the there shouldn't be any pairs in an array, remove the 'key', and keep the value:
$scope.dateDatas = ["29-09-2016", "30-09-2016", "01-10-2016", "02-10-2016", "03-10-2016"];
As a side note, remember also to put semicolon after the array.
$filter('date') will work on dates, not on strings. You first need to convert your initial string to a date object. I got the code to convert this string to Date from here. Also note that you need to decrease the month value by 1 before passing it to Date constructor because month in Date constructor is 0-based for some reason (expects 0 for January, 1 for February etc):
var splitValue = value.split("-");
var date = new Date(splitValue[2], splitValue[1] - 1, splitValue[0]);
The filter parameter should be 'yyyy-MM-dd' instead of 'yyyy-mm-dd' (capital M's), because small m's represent minutes instead of months and will give you this result:
["2016-00-29", "2016-00-30", "2016-00-01", "2016-00-02", "2016-00-03"]
Also check full example on plunker.

Trying to pass values to local storage using Sencha Touch 2.1.1

Can anyone tell me why this bit of code doesn't create an entry into localstorage?
myLocalStore.load();
var now = new Date();
var cardId = (now.getTime()).toString() + (this.getRandomInt(0, 100)).toString();
var entry1 = { id: cardId, dateCreated: now, title: 'The Title', narrative: 'the Text' };
var newRecord = new PinYin.model.Default(entry1);
myLocalStore.add(newRecord);
myLocalStore.sync();
console.log(entry1);
The console outputs
Object{id: "136575772251069", dateCreated: Fri Apr 12 2013 17:08:42 GMT+0800 (Taipei Standard Time), title: "The Title", narrative: "the Text"}
which is the correct format so im not sure what I'm doing wrong...
if I replace myLocalStore.add(entry1); with myLocalStore.add('value');
then i'll get the following inputted into the local storage
{"id":"ext-record-1","dateCreated":null,"title":null,"narrative":null}
I faced the same situation and found the solution like that,
First of all, if you set "idProperty" field of model, remove it.
After that, use the following convention.
myOfflineStore.add([{ listItemId: record.data.listItemId,
listItemTitle: record.data.listItemTitle,
listItemImageCode: record.data.listItemImageCode,
listItemNewPostCount: record.data.listItemNewPostCount }]);
Using [, ] is the key point.
EDIT: If you want to use idProperty, then you need to set the newly added record as "phantom" with setting phantom = true
Try like this...
var airline_name = res[i].AirLineName;
localStorage.setItem("AirlineCode3two",record.get('AirlineCode32'));
var stored_locally2 = {'ID2': i,'AirLineName2': res[i].AirLineName,};
//Adding our array to LocalStore(localStorage)
var localstore2 = Ext.getStore('TwowayStorage');
var twowayc1=localstore2.getCount();
localstore2.add(stored_locally2);
localstore2.sync();
localstore2.load();

Resources