calling a function inside mongoose hook 'post save' returns same doc - express

In my schema I'm having a post save hook like
DateInfoSchema.post('save', function (doc) {
var newDoc = helper. getListTimeRate(doc);
console.log(newDoc);
});
Then I'm having a helper module in that I'm having a function to calculate date range
lets consider 'doc' startdate and enddate so I want to calculate date range from start date to enddate
module.exports = {
getListTimeRate: function (data, yearEndDate) {
var toDate = new Date(),
weekName = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
Date.prototype.addDays = function(days) {
var dateAdd = new Date(this.valueOf());
dateAdd.setDate(dateAdd.getDate() + days);
return dateAdd;
};
function getDates(startDate, stopDate) {
var dateArray = [];
var currentDate = startDate;
if (currentDate == undefined){
while (currentDate <= stopDate) {
dateArray.push(currentDate);
currentDate = currentDate.addDays(1);
}
return dateArray;
}else {
var newCurrentDate = new Date(currentDate.toISOString().substr(0,10));
var newStopDate = new Date(stopDate.toISOString().substr(0,10));
while (newCurrentDate <= newStopDate) {
dateArray.push(newCurrentDate);
newCurrentDate = newCurrentDate.addDays(1);
}
return dateArray;
}
}
function calcRange(entry) {
// function get time
var dateList = [],
newList = [];
if (toDate < entry.endDate) {
// calc from endDate
newList = getDates(entry.startDate, entry.endDate);
//status often
selectDateFromOften();
} else {
if (yearEndDate) {
newList = getDates(entry.startDate, entry.endDate);
} else {
newList = getDates(entry.startDate, toDate);
}
// calc from toDate
//status often
selectDateFromOften();
}
function getDateTimeAnother() {
if (entry.hour) {
var setHour = entry.hour.getHours(),
setMin = entry.hour.getMinutes(),
setSecond = entry.hour.getSeconds();
}
dateList.forEach(function(entryDate){
entryDate.setHours(setHour);
entryDate.setMinutes(setMin);
entryDate.setSeconds(setSecond);
});
entry.rangeDate = dateList;
var compareUsedDate = [];
_.forEach(entry.frequencyId, function(value) {
compareUsedDate.push(value.dateRated);
});
entry.rangeDate = _.differenceBy(entry.rangeDate, compareUsedDate,Math.floor);
entry.rangeDate = entry.rangeDate.filter(function( element ) {
return element !== undefined;
});
console.log(dateList);
if (yearEndDate) {
return dateList;
}
}
function selectDateFromOften() {
switch(entry.oftenStatus) {
// Daily
case "0":
for (var i = 0; i< newList.length; i++) {
dateList.push(newList[i]);
}
getDateTimeAnother();
break;
//Weekly
case "1":
for (var i = 0; i< newList.length; i++) {
if (i == 0 || i % 7 == 0) {
dateList.push(newList[i]);
}
}
getDateTimeAnother();
break;
//Bi-Weekly
case "2":
for (var i = 0; i< newList.length; i++) {
if (i == 0 || i % 14 == 0) {
dateList.push(newList[i]);
}
}
getDateTimeAnother();
break;
//Monthly
case "3":
// for (var i = newList.length-1; i >= 0; i--) {
for (var i = 0; i< newList.length; i++) {
if (i == 0 || i % 28 == 0) {
dateList.push(newList[i]);
}
}
getDateTimeAnother();
break;
//Custom Date
case "4":
dateList = newList;
getDateCustom();
break;
default:
}
}
}
if (data.length) {
_.forEach(data, function(entry) {
if(entry.startDate != undefined){
calcRange(entry);
}
});
} else {
if(data.startDate != undefined){
calcRange(data);
}
}
return data;
}
};
But inside the hook 'newDoc' doesn't have 'rangeDate' field in it. Can anyone help me solve this issue? Thank you.

Related

Angular - can't sum point

I want to sum point but now I try write function and console.log(total) but it happens is 'undefined'
app.ts
saveTasks() {
if (this.tasksToSave.length != 0) {
for (let i = 0; this.tasksToSave.length > i; i++) {
this.ticketService.setAddTasks(
this.id,
this.tasksToSave[i]
)
}
}
}
sumPoint() {
let total = 0
if (this.tasksToSave.length != 0) {
for (let i = 0; i < this.tasksToSave.length; i++) {
total = total + this.tasksToSave[i].point
}
}
}
app.html
total = {{total}}
Put the total variable in the export block in the component like below:
export class YourComponent implements OnInit {
...
total: number = 0;
...
sumPoint() {
if (this.tasksToSave.length != 0) {
for (let i = 0; i < this.tasksToSave.length; i++) {
this.total = this.total + this.tasksToSave[i].point
}
}
}
...
}

Tedious node.js SQL connection; want to insert multiple values from an array

I'm running a loop and trying to insert the multiple values from an array while running it.
Here is the code:
function GetJobsToCourseID(index, jobData){
if((jobData != undefined)||(jobData != null)){
var extrArray = [];
for(var i = 0 ; i< jobData.length; i++){
extrArray = jobData[i];
for (var j=0; j<extrArray.length; j++)
{
console.log(extrArray[j]);
requestID = new Request("SELECT IDKey from dbo.Jobz where SubJobFamily ='"+extrArray[j]+"'", function(err, rowCount){
if (err) {
console.log(err);
}
else { connection111.reset(function(err){});
}
});
}
}
}
requestID.on('row', function(columns) {
for (var i = 0; i <columns.length; i++)
{
console.log(columns[i].value, "Please work");
if (columns[i].value == null || columns[i].value == undefined) {
console.log('NULL');
} else {
}
}
connection111.execSql(requestID);
});
}
As you can see I'm trying to insert the j element of my tempArray(I dont think it should work anyways, because of how Tedious connections work)
What would be the approach then - extracting each array element and populating it withing the SQL table using Tedious?
Fixed it by adding a connection pool and an changing the second loops var j to let j ... 'tedious' is really tedious...
here is the code:
function GetJobsToCourseID(index, jobData){
if((jobData != undefined)&&(jobData != null)){
var extrArray = [];
var newArray = [];
for(var i = 0 ; i< jobData.length; i++){
extrArray = jobData[i];}
for (let j=0; j<extrArray.length; j++){
pool.acquire(function (err, connection1111) {
if (err)
console.error(err);
requestID = new Request("SELECT IDkey from dbo.Jobz where SubJobFamily ='"+extrArray[j]+"'", function(err, rowCount){
if (err) {
console.log(err);
}
else {connection1111.reset(function(err){});}});
requestID.on('row', function(columns) {
for (var i = 0; i <columns.length; i++){
if (columns[i].value == null || columns[i].value == undefined) {
console.log('NULL');
} else {
arty.push(columns[i].value);
console.log(arty);
}}
});
connection1111.execSql(requestID);
});}
pool.on('error', function (err) {
console.error(err);
});
}}

How to fetch dynamic table list in MVC and angularJS

I'm getting a list in my angular.js file (EditDeleteItem.js) which I'm making based on the selected table name.
The function to send my list is as below:-
$scope.SaveTblRecord = function (list) {
//alert(JSON.stringify($scope.employeeList));
$scope.FetchTableName();
//var Data = $.param({ TblData: $scope.MyTblDataList });
var itemList = [];
angular.forEach(list, function (value, key) {
if (list[key].selected) {
itemList.push(list[key].selected);
}
});
$scope.ItemsList = [];
$scope.ItemsList = itemList;
$http({
method: "Post",
url: "/Admin/SaveTblData",
data: $scope.ItemsList,
}).success(function (data) {
$scope.GetTblData($scope.TempName);
}).error(function (err) {
alert(err.Message);
})
};//SaveTblRecord
Now in my Controller I want to fetch that list based on the selected table name but I can't do it :-
public JsonResult SaveTblData(List<LocationTbl> NewTblList) //Need To Have TableName here instead of LocationTbl so that selected table name list is fetched.
{
string MyTableName = Convert.ToString(TempData["TableName"]);
try
{
if (NewTblList == null)
{
return new JsonResult { Data = "Empty Selection", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
else {
using (EBContext db = new EBContext())
{
bool results = false;
Type tableType = typeof(CourseDesc);
switch (MyTableName)
{
//case "CourseTbl":
// for (int i = 0; i < NewTblList.Count; i++)
// {
// var CtObj = NewTblList[i];
// CourseTbl ct = db.Courses.AsNoTracking().FirstOrDefault(x => x.ID == CtObj.ID);
// results = UtilityMethods<CourseTbl, int>.EditEntity(db, CtObj);
// }
// break;
//case "CourseDescTbl":
// for (int i = 0; i < NewTblList.Count; i++)
// {
// var CdtObj = NewTblList[i];
// CourseDesc cd = db.CourseDesc.AsNoTracking().FirstOrDefault(x => x.ID == CdtObj.ID);
// results = UtilityMethods<CourseDesc, int>.EditEntity(db, CdtObj);
// }
// break;
//case "CourseSubDesc":
// for (int i = 0; i < NewTblList.Count; i++)
// {
// var CsdObj = NewTblList[i];
// CourseSubDesc csd = db.CourseSubDesc.AsNoTracking().FirstOrDefault(x => x.ID == CsdObj.ID);
// results = UtilityMethods<CourseSubDesc, int>.EditEntity(db, CsdObj);
// }
// break;
//case "InternTbl":
// for (int i = 0; i < NewTblList.Count; i++)
// {
// var ItObj = NewTblList[i];
// InternShip It = db.Interns.AsNoTracking().FirstOrDefault(x => x.ID == ItObj.ID);
// results = UtilityMethods<InternShip, int>.EditEntity(db, ItObj);
// }
// break;
case "LocationTbl":
for (int i = 0; i < NewTblList.Count; i++)
{
var LtObj = NewTblList[i];
LocationTbl lt = db.Loc.AsNoTracking().FirstOrDefault(x => x.ID == LtObj.ID);
results = UtilityMethods<LocationTbl, int>.EditEntity(db, LtObj);
}
break;
}
var resultList = new List<object>();
foreach (var item in db.Set(tableType))
{
resultList.Add(item);
}
return new JsonResult { Data = resultList, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
}
catch (Exception ex)
{
return new JsonResult { Data = ex.Message, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
I've been searching the internet for a while and found some related links like Link1
and Link2
But I can't find solution to my problem. Please HELP!!

GMaps API - calc route driving into pedestrian area

my calculated route works good so far, but I have some trouble with my destination address.
When the destination is within a pedestrian area (city center), this destination (lat, long) will set to the next valid street. This is probably how it supposed to be, but it's important that I get the route until the specific destination address. What I want: E.g. I drive into the pedestrian area or I drive as far as possible by car and then walk to the destination.
Anyone has an idea how I can solve this problem? I am using the following code, the code works so that is not the problem:
<script type="text/javascript">
var directionsDisplay = new google.maps.DirectionsRenderer({
animation: google.maps.Animation.DROP,
draggable: true
});
var directionsService = new google.maps.DirectionsService();
var map;
var geocoder;
var resultsInput;
var question;
var routeStart, routeEnd;
var travMode;
var frage_gruppen_nr;
var zsf1,zsf2;
var zentrieren;
function initialize() {
geocoder = new google.maps.Geocoder();
routeStart = $('.multiple-short-txt:eq(0) .text:eq(0)');
routeEnd = $('.multiple-short-txt:eq(0) .text:eq(1)');
coords_field_map = $('.text-short:eq(1) .text:eq(0)');
coords_field_map.hide();
zsf1 = $('.multiple-short-txt:eq(1) .text:eq(0)');
zsf2 = $('.multiple-short-txt:eq(1) .text:eq(1)');
var aktuelle_frage = 'r1';
var frage_gruppen_nr = parseInt(aktuelle_frage.substr(1));
frage_gruppen_nr = frage_gruppen_nr - 1;
if(frage_gruppen_nr>1){
routeStart.val('xxxx');
var coords;
var ziel_vorfrage = 'abc';
alert(ziel_vorfrage);
geocoder.geocode( { 'address': ziel_vorfrage}, function(results1, status1) {
if (status1 == google.maps.GeocoderStatus.OK) {
coords = String(results1[0].geometry.location)
}
});
zentrieren = new google.maps.LatLng(coords);
}else{
zentrieren = new google.maps.LatLng(49.759578, 6.644134);
}
travMode = document.getElementsByTagName("SELECT")[0];
question = '{SGQ}_c';
var mapOptions = {
zoom:12,
center: zentrieren
};
map = new google.maps.Map(document.getElementById('gmap_canvas_'+question), mapOptions);
google.maps.event.addListener(directionsDisplay, 'directions_changed', function(event) {
var directions = this.getDirections();
var overview_path = directions.routes[0].overview_path;
var startingPoint = overview_path[0];
var destination = overview_path[overview_path.length - 1];
if (typeof startLatlng === 'undefined' || !startingPoint.equals(startLatlng)) {
startLatlng = startingPoint;
getLocationName(startingPoint, function(name) {
routeStart.val(name);
});
}
if (typeof endLatlng === 'undefined' || !destination.equals(endLatlng)) {
endLatlng = destination;
getLocationName(destination, function(name) {
routeEnd.val(name);
});
}
//alert('startpoint: '+startingPoint);
calculateDistances(startingPoint, destination);
});
directionsDisplay.setMap(map);
resultsInput = $('.text-long:eq(0) .textarea');
$(resultsInput).attr('readonly', true);
}
function calcRoute() {
var coords;
var coords2;
var start = routeStart.val();
geocoder.geocode( { 'address': start}, function(results1, status1) {
if (status1 == google.maps.GeocoderStatus.OK) {
coords = String(results1[0].geometry.location)
}
else {
alert('Die Startadresse konnte nicht gefunden werden.');
}
});
var end = routeEnd.val();
geocoder.geocode( { 'address': end}, function(results2, status1) {
if (status1 == google.maps.GeocoderStatus.OK) {
coords2 = String(results2[0].geometry.location)
}
else {
alert('Die Zieladresse konnte nicht gefunden werden.');
}
});
var selectedMode;
if(travMode.value == 1){
selectedMode = 'DRIVING';
}else if(travMode.value == 2){
selectedMode = 'BICYCLING';
}else if(travMode.value == 3){
selectedMode = 'TRANSIT';
}else if(travMode.value == 4){
selectedMode = 'WALKING';
}
//
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode[selectedMode]
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
function calculateDistances(origin, destination) {
var selectedMode;
//select travel mode
if(travMode.value == 1){
selectedMode = 'DRIVING';
}else if(travMode.value == 2){
selectedMode = 'BICYCLING';
}else if(travMode.value == 3){
selectedMode = 'TRANSIT';
}else if(travMode.value == 4){
selectedMode = 'WALKING';
}
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [origin],
destinations: [destination],
travelMode: google.maps.TravelMode[selectedMode],
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback);
}
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
$(resultsInput).val('Startaddresse: '+origins[i]+'\n\nReiseziel: '+destinations[j]+'\n\nDistanz: '+results[j].distance.text+'\n\nZeit: '+results[j].duration.text+'');
//save result to fields
zsf1.val(results[j].distance.text);
zsf2.val(results[j].duration.text);
}
}
}
}
function getLocationName(latlng, callback) {
geocoder.geocode({
location: latlng
}, function(result, status) {
if (status === google.maps.GeocoderStatus.OK) {
var i = -1;
console.log(result);
// find the array index of the last object with the locality type
for (var c = 0; c < result.length; c++) {
for (var t = 0; t < result[c].types.length; t++) {
if (result[c].types[t].search('locality') > -1) {
i = c;
}
}
}
var locationName = result[0].formatted_address;
callback(locationName);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>

FBJS image slider

Im trying to recreate a slider similar to:
http://www.facebook.com/BacardiLimon?v=app_146177448730789
but apparently there is zero documentation on how to do something like this with FBJS :'(
var eCardPos = 0;
var totalCards = 4;
var animationFadeTime = 300;
var cardUrls = [];
cardUrls[0]= '';
cardUrls[1]= '';
cardUrls[2]= '';
cardUrls[3]= '';
function changeEcardPrev()
{
eCardPos--;
if (eCardPos < 0) {
eCardPos = totalCards-1;
}
showEcard();
}
function changeEcardNext()
{
eCardPos++;
if (eCardPos > totalCards-1) {
eCardPos = 0;
}
showEcard();
}
function changeEcard(pos)
{
eCardPos = pos;
showEcard();
}
function showEcard()
{
var elCard = document.getElementById('cardImage');
var elLink = document.getElementById('cardLink');
var elPreload = document.getElementById('preload_card_'+eCardPos);
for (var i=0;i<totalCards;i++)
{
document.getElementById('cardButton_'+i).removeClassName('active');
}
document.getElementById('cardButton_'+eCardPos).addClassName('active');
elLink.setHref(cardUrls[eCardPos]);
Animation(elCard).to("opacity", 0).duration(animationFadeTime).checkpoint(1, function() {
elCard.setSrc(elPreload.getSrc());
}).to("opacity", 1).duration(animationFadeTime).go();
//Animation(elCard).to("opacity", 1).duration(animationFadeTime).go();
}
I happened to find the src but I dont even know where to start :\
EDIT:
I think I found something that might help but the images slide :\ I just want them to appear when a direction is pressed.
var numslides = 3;
var slidesvisible = 1;
var currentslide = 0;
var slidewidth = 300;
function goright() {
if (currentslide <= (numslides-slidesvisible-1)) {
Animation(document.getElementById('slideshow_inner')).by('right', slidewidth+'px').by('left', '-'+slidewidth+'px').go();
if (currentslide == (numslides-slidesvisible-1)) {
Animation(document.getElementById('right_button')).to('opacity', '0.3').go();
Animation(document.getElementById('left_button')).to('opacity', '1').go();
}
if (currentslide < (numslides-slidesvisible-1)) { Animation(document.getElementById('left_button')).to('opacity', '1').go(); }
currentslide++;
}
}
function goleft() {
if (currentslide > 0) {
Animation(document.getElementById('slideshow_inner')).by('left', slidewidth+'px').by('right', '-'+slidewidth+'px').go();
if (currentslide == 1) {
Animation(document.getElementById('left_button')).to('opacity', '0.3').go();
Animation(document.getElementById('right_button')).to('opacity', '1').go();
}
if (currentslide > 1) { Animation(document.getElementById('right_button')).to('opacity', '1').go(); }
currentslide--;
}
}
How would I get the image to fade in and out rather than slide?