based on this Mongoose embedded documents / DocumentsArrays id
i try to implement a condition in a loop inside a loop. At the end, the new "tosave" Comments Object should contain the _id from the BlogPost based on "where a_id = b_id".
I use node,express and mongoose.
I have a multi row form with multiple BlogPosts and a Blogpost can have multiple Comments.
On the Backend, i have 2 Arrays -> BlogPosts and Comments like this:
BlogPosts: [{ a_id: '1', name: 'name1' },
{ a_id: '2', name: 'name2' },
{ a_id: '3', name: 'name3' }],
Comments: [{ b_id: '1', name: 'comment for BlogPost name1' },
{ b_id: '1', name: 'other comment for BlogPost name1' },
{ b_id: '3', name: 'comment for BlogPost name3' }],
I need the _id from a Blogpost Document inside every Comment, to reference between Comments and Blogposts.
I loop over the BlogPosts like this:
var new_post_to_save = [];
for(var i=0; i<req.body.blogposts.length;i++) {
var newpost = new BlogPost();
console.log('blogpost nr : ' + [i] + ' has new _id: ' + newpost._id );
newpost.name = req.body.blogposts[i].name,
newpost.a_id = req.body.blogposts[i].a_id
new_post_to_save.push(newpost);
},
This is working fine. I get a new Array "new_post_to_save", witch i can save easy.
Now i try to loop inside BlogPosts to give every Comment the _id Field from the new created "newpost" Object.
What i try - but it failed.. It matches all Comments to all BlogPosts.
var new_post_to_save = [];
var new_comment_to_save = [];
for(var i=0; i<req.body.blogposts.length;i++) {
var newpost = new BlogPost();
console.log('blogpost nr : ' + [i] + ' has new _id: ' + newpost._id );
newpost.name = req.body.blogposts[i].name,
newpost.a_id = req.body.blogposts[i].a_id
// here a loop to create x Comments with the _id from newpost and
// the condition: IF a_id = b_id
// then create new Comment and get die _id from his Blogpost
for(var f=0; f<req.body.comments.length;f++) {
if (newpost.a_id = req.body.comments[f].b_id)
console.log(' Yea ! Comment ' + [f] + ' matches Blogpost Nr. ' + [i]);
var newcomment = new CommentModel();
newcomment.id_newpost = newpost._id,
newcomment.name = req.body.comments[f].name,
newcomment.b_id = req.body.comments[f].b_id,
}; // end if
}; // end for
new_comment_to_save.push(newcomment);
new_post_to_save.push(newpost);
}, // end for
This is my first question here.
Any ideas ? Thanks so much
I am not familair with Mongoose, just looking at your code, seems you have a little mistake in code: position of: new_comment_to_save.push(newcomment); it should be in the if because only when they match you want them added..
var new_post_to_save = [];
var new_comment_to_save = [];
for(var i=0; i<req.body.blogposts.length;i++) {
var newpost = new BlogPost();
console.log('blogpost nr : ' + [i] + ' has new _id: ' + newpost._id );
newpost.name = req.body.blogposts[i].name,
newpost.a_id = req.body.blogposts[i].a_id
// here a loop to create x Comments with the _id from newpost and
// the condition: IF a_id = b_id
// then create new Comment and get die _id from his Blogpost
for(var f=0; f<req.body.comments.length;f++) {
if (newpost.a_id = req.body.comments[f].b_id)
console.log(' Yea ! Comment ' + [f] + ' matches Blogpost Nr. ' + [i]);
var newcomment = new CommentModel();
newcomment.id_newpost = newpost._id,
newcomment.name = req.body.comments[f].name,
newcomment.b_id = req.body.comments[f].b_id,
new_comment_to_save.push(newcomment);
}; // end if
}; // end for
new_post_to_save.push(newpost);
}, // end for
Related
I have a spreadsheet where a user can list classes and Google Classroom enrollment codes, represented by the array userClassCodes. This array is allowed to contain blank values when the range contains blank cells. This array is represented in the following way:
[ ['class name 01', 'class code 01'], ['class name 02', 'class code 02'], ...]
I am using the Google Classroom API to get a list of the sheet user's enrollment codes and course IDs. I would like to iterate through the userClassCodes array and add the class ID to the array when there is a matching class code in the API response. If there is no match, I would like to preserve the entry in the array and add a blank value for the course ID.
I am having trouble properly constructing an array that will achieve the desired output. Here is my current code:
function googleClassroomImport() {
var userClassCodes = SpreadsheetApp.getActive().getRange("Sheet1!A1:B25").getValues();
var newArray = [];
var options = {
teacherId: 'me',
courseStates: 'ACTIVE',
pageSize: 50
};
var response = Classroom.Courses.list(options);
response.courses.forEach(function (course) {
for (let i = 0; i < userClassCodes.length; i++) {
if (userClassCodes[i][1] == course.enrollmentCode) {
newArray.push([userClassCodes[i][0], userClassCodes[i][1], course.id]);
}
else {
newArray.push([userClassCodes[i][0], userClassCodes[i][1], ""]);
}
}
});
console.log(newArray);
}
Try this:
function googleClassroomImport() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName("Sheet0");
const rg = sh.getRange("A1:B25");
const vs = rg.getValues().filter(r => r[0] && r[1]).filter(e => e);
const arr = vs.map(r => r[1]);
var options = { teacherId: 'me', courseStates: 'ACTIVE', pageSize: 50 };
var response = Classroom.Courses.list(options);
response.courses.forEach(course => {
let idx = arr.indexOf(course.enrollmentCode);
if (~idx) {
vs[idx].push(course.id);
} else {
vs[idx].push('');
}
});
console.log(newArray);
}
I am developing an application with local notifications with values coming from the database. However, it is repeating the notification with the same value countless times until changing to another.
Example:
1st - "The invoice of house #1 will expire"
2nd - "The invoice of house #1 will expire"
3rd - "The invoice of house #2 will expire"
Any idea what that might be and how to fix it?
calculateDif(idHouse, dateBill) {
let billDate= moment(dateBill);
var MyDate = new Date();
var MyDateString;
MyDateString = MyDate.getFullYear() + '-' + ('0' + (MyDate.getMonth()+1)).slice(-2)
+ '-' + ('0' + MyDate.getDate()).slice(-2);
let warningDate= billDate.diff(MyDateString, 'days');
if (warningDate <= 5) {
this.localNotifications.schedule({
id: 1,
text: 'The invoice of house ' idHouse + ' will expire',
sound: null,
data: { secret: 1 }
});
}
}
I think the problem is in the function that execute calculateDif();
You can also create an array of your articles that you have already notified, for example notifiedHouses = []
and check if the id is already notified using .some
calculateDif(idHouse, dateBill) {
let billDate= moment(dateBill);
var MyDate = new Date();
var MyDateString;
MyDateString = MyDate.getFullYear() + '-' + ('0' + (MyDate.getMonth()+1)).slice(-2)
+ '-' + ('0' + MyDate.getDate()).slice(-2);
let warningDate= billDate.diff(MyDateString, 'days');
if (warningDate <= 5 && !this.notifiedHouses.some( item => item.idHouse === idHouse )) {
this.localNotifications.schedule({
id: 1,
text: 'The invoice of house ' idHouse + ' will expire',
sound: null,
data: { secret: 1 }
});
const house = {idHouse: idHouse}
this.notifiedHouses.push(house);
}
}
Could anyone point me in the correct direction?
I searched plenty... I had no luck with mapping... or "find" nor extracting the data I need.
My code:
function checkMeetCode(meetCode, index, searchDate) {
var ss=SpreadsheetApp.getActive().getSheetByName('AsistenciaMeet');
var colB = ss.getRange("D3:D").getValues();
var filasLlenasLengthB = colB.filter(String).length; //
var userKey = 'all';
var applicationName = 'meet';
var emailAddress = colB[index];
Logger.log("Index / Alumno: "+index+" / " + emailAddress);
var optionalArgs = {
event_name: "call_ended",
endTime: searchDate,
startTime: fechaRestada(searchDate),
filters: "identifier==" + emailAddress + ",meeting_code==" + meetCode
};
var response = AdminReports.Activities.list(userKey, applicationName, optionalArgs)
Logger.log("RESPONSE: "+response);
var actividad = response.items;
if (actividad == null) {
// do nothing
}
else {
**// HERE IS WHERE I AM TRYING TO FIND / EXTRACT INFORMATION FROM "response"
// READ BELOW PLEASE.**
}
}
NEED HELP WITH:
I want to FIND/EXTRACT the intValue of "duration_seconds":
The results from:
Logger.log("RESPONSE: "+response);
RESPONSE: {"kind":"admin#reports#activities","etag":"\"JDMC8884sebSctZ17CIssbQ/IhilrSKVziEhoZ7URUpQ-NrztHY\"","items":[{"events":[{"parameters":[{"name":"video_send_seconds","intValue":"1829"},{"name":"screencast_recv_packet_loss_mean","intValue":"0"},{"name":"identifier_type","value":"email_address"},{"name":"video_send_packet_loss_max","intValue":"0"},{"name":"endpoint_id","value":"meet_android_4154513448557872"},{"name":"video_recv_long_side_median_pixels","intValue":"320"},{"name":"calendar_event_id","value":"44jr4vu3qo75q6bvkknq_20200421T213000Z"},{"name":"video_send_fps_mean","intValue":"29"},{"name":"video_recv_short_side_median_pixels","intValue":"180"},{"name":"network_estimated_download_kbps_mean","intValue":"351"},{"name":"duration_seconds","intValue":"1830"},{"name":"video_send_bitrate_kbps_mean","intValue":"762"},{"name":"network_recv_jitter_msec_max","intValue":"130"},{"name":"ip_address","value":"186.59.21.55"},{"name":"audio_send_seconds","intValue":"1829"},{"name":"screencast_recv_packet_loss_max","intValue":"0"},{"name":"video_recv_seconds","intValue":"1818"},{"name":"network_rtt_msec_mean","intValue":"36"},{"name":"video_send_long_side_median_pixels","intValue":"640"},{"name":"screencast_recv_seconds","intValue":"1829"},{"name":"product_type","value":"meet"},{"name":"video_recv_packet_loss_max","intValue":"0"},{"name":"is_external","boolValue":false}],"name":"call_ended","type":"call"}] ...
OK, after roughly 8 hours... I was able to make it work.
var insideParameters = response["items"][0]["events"][0]["parameters"];
Logger.log(insideParameters.length);
for (var i = 30; i<insideParameters.length;i++){ // its always located above i = 30...
if(insideParameters[i].name === "duration_seconds"){
var duration = insideParameters[i].intValue;
Logger.log(duration);
}
}
So im trying to automaically retrieve a random entry from an array listed in a seperate node.js file
function code
var replies = require('./replies');
function followed(event) {
var name = event.source.name;
var flname = event.source.screen_name;
var myArray = [replies];
var item = myArray[(Math.random()*myArray.length)|0];
var followtweet = '#' + flname + item;
if(flname != "UserName") {
tweetIt(followtweet);
console.log('\n#' + flname + ' Followed You');
console.log('\nYou Tweeted:\n ' + followtweet);
} else {
console.log(' Interferance From Another Bot! \n');
}
}
External Array
module.exports = {
followedone: 'one',
followedtwo: 'two',
followedthre: 'three',
replyone: ' one',
replytwo: ' two',
replythre: ' three',
}
When I Run This and the function runs i get this
#LandscapesLucid Followed You
You Tweeted:
#LandscapesLucid[object Object]
Waiting For The Next Action
I'm not sure why its only showing the [object Object] instead of either one two or three like in the array
Can you try to change from this
var item = myArray[(Math.random()*myArray.length)|0];
to this?
var item = myArray[Math.floor(Math.random()*items.length)];
What I'm trying to achieve:
Change state when the user clicks previous or next, each state is assigned an id and will need to figure out which id is previous or next before changing previous or next state.
Current Problem:
I have managed to display the current state id '1' and I have managed to group all the other id's within an array but I don't know how to get the next and previous buttons to trigger the right previous or next states on click.
Please find my code below, I've added comments/notes to point things out.
Any help/advice would be helpful! Thank you.
Controller JS
// -- Current Page ID, '1' -- //
var currentID = $stateParams.id;
// -- Body Type, 'triangle' -- //
var bodyType = $scope.$storage.userData.bodyType.bodyType;
// -- Dress Array, [{"id": "1", "bodyType": "triangle"},{"id": "2", "bodyType": "triangle"},{"id": "3", "bodyType": "round"},{"id": "4", "bodyType": "triangle"}] --//
var dressArray = $scope.$storage.appData.dresses;
// -- Remove anything that doesn't match the current body Type e.g Remove 'round' -- //
var removeRound = $filter('filter')(dressArray, function(value, index) {return value.bodyType == bodyType;});
// -- Dress Array -- //
$scope.dressArray = [];
// -- Push each filter value to Array, ["1", "2", "4"] -- //
angular.forEach(removeRound, function(value, key) {
$scope.dressArray.push(value.id);
});
// -- Console Test, ["1", "2", "4"] -- //
console.log($scope.dressArray);
// -- If currentID = '1', The next button should display '2' -- //
// -- If currentID = '2', The next button should display '4'--//
$scope.nextDress = function() {
$state.go('main.rail', {id: idhere });
};
// -- If currentID = '1', The previous button should display '4' -- //
// -- If currentID = '2', The previous button should display '1' -- //
$scope.previousDress = function() {
$state.go('main.rail', {id: idhere });
};
HTML
<li class="next"><md-button ng-click="nextDress()">Next</md-button></li>
<li class="previous"><md-button ng-click="previousDress()">Previous</md-button></li>
check that the currentId + 1 is not greater than the length of the array for the next item (if greater, go to the first) and check that the currentId - 1 is not less than 0, if yes, go to the last item (to make it cyclic):
$scope.nextDress = function() {
var next = parseInt(currentId) + 1 > dressArray.length ? 0 : parseInt(currentId) + 1;
$state.go('main.rail', {id: next });
};
$scope.previousDress = function() {
var prev = parseInt(currentId) - 1 < 0 ? dressArray.length - 1 : parseInt(currentId) - 1;
$state.go('main.rail', {id: prev });
};
I would make the data like a closed linked list, run this every time after passing through filter.
var currentItem; // keep a reference of current item
var arrayToLL = function(arr){
for (var i = 0; i < arr.length; i++) {
var item = arr[i];
if (i == 0) item.prev = arr[arr.length - 1];
else item.prev = arr[i - 1];
if (i == arr.length - 1) item.next = arr[0];
else item.next = arr[i + 1];
if (item.id == currentId) { // you may get currentId from $stateParams
currentItem = item;
}
}
}
$scope.nextDress = function() {
$state.go('main.rail', {id: currentItem.next.id });
};
$scope.previousDress = function() {
$state.go('main.rail', {id: currentItem.prev.id });
};