I made this code today, and i don't nkow what's the problem? In theory, the findOne() function should work for() each loop of the for. And this is not that what happen. In the array there are several elements, and i want to save all of this. I'm newbie in NodeJS, but the loop for() always is the same, or not?
var sType = models.Type; // Model Mongoose
var word = ''; // Word
var i = 0;
for( i = 0; i < arrayData.length; i++ ){
word = arrayData[i]; // Save the element in word, I made this to try to pass the variable.
sType.findOne({ nameType: word }, { _id : 1 }, function( err, type ){
console.log( word ); // In the console, show me the last element of array x20.
if( err )
throw err;
if( !err && type == null ){
var types = new sType({
nameType: word
});
types.save( function( err ){
if( err )
throw err;
});
}
});
}
If I don't create the variable 'word', the program throw me a mistake 'Validation Error: Path 'nameTYpe' is required.'
If you use the method findOne inside a loop, you need to wait the callback, try to use the library async.js,
here is an example:
async.eachSeries(arrayData, function(data, dataCallback) {
sType.findOne({}, {}, function( err, type ) {
//your code after the findOne method
//return to the next element of array
dataCallback();
}
}, function done() {
console.log("loop end");
});
Related
im geting data from Db using php at first for building a table , later im geting new json data from socket and updating $scope, what i need is to push values that not exist in $scope.
angular.forEach(event.market, (market ,keym) => {
angular.forEach($scope.users.results, function(value, key) {
if(value.marketId == keym) // keym = new marketId from socket
{
//do nothing
}
else
{
//push(new valuse);
}
});
});
the problem im having is that if a marketId dosent match any keys that i allready have then it pushes the amount of times it didnt match instead of pushing 1 time if it didnt match.
what am i doing wrong?
thanks
Before doing push into some array, check whether marketId dose not match any keys and not present in array as well. So in else you will have to add conditions for marketId check and array check.
From what I understand you want to add in an array, missing objects. I think what you are trying to do can be simply achieved by:
angular.forEach(event.market, (valueM, keyM) => {
let isDuplicate = $scope.users.results.filter(user => /* some validation here */).length > 0;
if(!isDuplicate) {
// push new values
}
})
that solved my issue :
angular.forEach(game.market, (market, keym) => {
var addToArray = true;
for (var i = 0; i < $scope.users.results.length; i++) {
if ($scope.users.results[i].marketId == keym) {
addToArray = false;
}
}
if (addToArray) {
$scope.users.results.push({
marketId: keym,
marketName: market.name
});
}
$scope.users.results.marketName = ' ';
$scope.users.results.marketId = ' ';
});
thanks
I am having issues checking if the string value in my array is true in a cell.
function myFunction() {
var People = ['Amanda', 'John'];
for (var n in People )
{
if( People[0] == true);
Logger.log("BOOKED");
}
else{
Logger.log("FREE");
}
}
Plenty of issues with the code!
Does this do it ?
function myFunction() {
var People = ['Amanda', 'John'];
for (var n=0;n<People.length;n++) {
if( People[n] ) {
Logger.log("BOOKED");
}
else {
Logger.log("FREE");
}
}
}
I'm not sure if you just want to test for members of the array being present, or if you want to test actual names in the array
I have chainable promises which are working fine in a single series but now i want to call this serios of chain inside for loop but it does not work as expected.
see my demo plunker and see the output in console.
below is the structure of my chaining promises . I want all publicIP which is returned by funTwo; but I want to complete funThree() and then want to get all publicIP. As I know that $q.when() makes a value in promise object.
but you can see that console.log('pA', promiseArray); executed very before and console.log('res three'); and why successHandler and finally called before that?
Here surely I am missing something , may be have to write a return; in proper place , kindly help me how to executed all function in for loop and return a data array after that for loop ends which can be retried in successHandler
MyService.funZero()
.then(function(response) {
console.log(response);
var promiseArray = [];
for(var i = 0; i < 2 ; i++) {
console.log('I', i);
MyService.funOne()
.then(MyService.funTwo)
.then(function(res2) {
console.log('res two', res2);
publicIP = res2.ip;
console.log('i', publicIP);
promiseArray.push({'ip': publicIP});
return MyService.funThree(publicIP);
})
.then(function() {
console.log('res three');
})
} // for loop ends
console.log('pA', promiseArray);
return $q.when(promiseArray);
})
.then(function(res4){
console.log('after for loop', res4);
})
.then(successHandler)
.catch(errorHandler)
.finally(final, notify);
So, I'm not sure exactly what MyService.funThree does, but you can aggregate an array via ipArray.push({'ip': publicIP}) and return that to the MyService.funThree and then the subsequent function. The issue here is there is no guarantee of order in the ipArray if that's what you're looking for. Here's the middle section of that function:
ipArray = [];
for(var i = 0; i < 2 ; i++) {
console.log('I', i);
var promise = MyService.funOne()
.then(MyService.funTwo)
.then(function(res2) {
console.log('res two', res2);
publicIP = res2.ip;
console.log('i', publicIP);
ipArray.push({'ip': publicIP});
return ipArray;
})
.then(MyService.funThree)
.then(function() {
console.log('res three');
});
promiseArray.push(promise);
}
console.log('pA', promiseArray);
return $q.all(promiseArray);
I'm looking for a AngularJS-based way to prevent multiple submits per task.
I don't need buttons to be disabled after submission or close the form and wait for the task to be completed. Instead, I need requests to be unique.
To be more detailed, I need $http.get and $http.post stop sending multiple same requests.
Any Ideas?
According to this article, you can use provider decorator.
NOTE: this approach is based on angular-api
https://gist.github.com/adambuczynski/354364e2a58786e2be71
UPDATE
I've changed a little part in your suggested solution, because returned promises have lost .success and .error and .then.
Just use this edited code to have all of those functions working:
.config(["$provide", function ($provide) {
$provide.decorator('$http', function ($delegate, $q) {
var pendingRequests = {};
var $http = $delegate;
function hash(str) {
var h = 0;
var strlen = str.length;
if (strlen === 0) {
return h;
}
for (var i = 0, n; i < strlen; ++i) {
n = str.charCodeAt(i);
h = ((h << 5) - h) + n;
h = h & h;
}
return h >>> 0;
}
function getRequestIdentifier(config) {
var str = config.method + config.url;
if (config.data && typeof config.data === 'object') {
str += angular.toJson(config.data);
}
return hash(str);
}
var $duplicateRequestsFilter = function (config) {
if (config.ignoreDuplicateRequest) {
return $http(config);
}
var identifier = getRequestIdentifier(config);
if (pendingRequests[identifier]) {
if (config.rejectDuplicateRequest) {
return $q.reject({
data: '',
headers: {},
status: config.rejectDuplicateStatusCode || 400,
config: config
});
}
return pendingRequests[identifier];
}
pendingRequests[identifier] = $http(config);
$http(config).finally(function () {
delete pendingRequests[identifier];
});
return pendingRequests[identifier];
};
Object.keys($http).filter(function (key) {
return (typeof $http[key] === 'function');
}).forEach(function (key) {
$duplicateRequestsFilter[key] = $http[key];
});
return $duplicateRequestsFilter;
})
}])
It could be a performance issue but following idea could solve your problem.
Store the each request URL and DATA as key value pair on a variable. URL should be KEY. For Same URL multiple submission can be stored in a Array.
Then for any new call check the URL if it present in your stored object, then compare the data with each object thorughly (deep check, it is costly though).
If any exact match found then stop the processing. As same request came.
Other wise proceed and don't forget to store this data also.
But it is costly since need to check the data which could be havy.
Note: At the time of storing the data you could convert it to JSON String so it will be easier to compare between String.
here is the Code Algo
YourService.call(url, params) {
var Str1 = JSON.stringify(params);
if(StoredObj[url]) {
for each (StoredObj[url] as Str){
if(Str === Str1) {
return;
}
}
}
else {
StoredObj[url] = []; //new Array
}
StoredObj[url].push(Str1);
Call $http then;
}
I have an array from my API that prints like this:
Array [Object, Object, Object, Object, Object]
// if stringified
[{"id":"0","name":"user1","type":"mf","message":"bonjour user1"},
{"id":"1","name":"user2","type":"ff","message":"hello user2"},
{"id":"2","name":"user3","type":"mm","message":"konnichiwa user3"},
{"id":"3","name":"user4","type":"mf","message":"ni hao user4"},
{"id":"4","name":"user5","type":"ff","message":"high 5! user5"}]}
I have an input named content and I would like to see if it matches any of the name in the array; if it does, which id is it; if it's not, the id would be 0.
Eg. if user enters user3, the id would be 2; and if user enters user9, the id would be 0.
I have been struggling to get the value of name from this nested array and below is what I have tried... and the whole code is here. It would be very nice if someone could tell me where have I done wrong:
var data = {};
$.ajax({
url: googleApi,
headers: {
"Authorization": "Basic " + btoa(googleKey + ":" + googleSecret)
},
data: data,
dataType: 'json',
type: 'GET',
success: function(data) {
console.log(data);
console.log(JSON.stringify(data));
function getID(name){
if (name.name == content){
console.log ("matching name" + name.name);
return getID(name.name);
} else {
return name;
}
}
alert(getID(data).id);
return false;
},
error: function(data) {
console.log("ERROR: " + data);
}
});
Updated Answer:
Dont alert the function, just alert the answer inside the loop when it matched.
I typed alexis in the textbox and the output was 1
I have edited my answer.Check it, this is what you have to do in your case:
function getID(name) {
$.each(data,function(key,value){
$.each(value,function(key1,value1){
console.log(value);
if(value1 == content){
alert(value.id);
return;
}
});
});
}
getID(data);
return false;
Take a look at the updated fiddle Fiddle Example
Second Update:
You do not have to use else if condition, simply use a variable to check whether there has been any matches.
You create a empty variable and while looping through the array check whether there is a match and if there is a match, you just feed the variable with that id value and later you will check whether the variable is empty or not and based on that alert(0);
Checkout the Latest Updated Fiddle
As you are using jQuery, you can use the grep function which is intended for searching an array:
var contentArray = [{"id":"0","name":"user1","type":"mf","message":"bonjour user1"},
{"id":"1","name":"user2","type":"ff","message":"hello user2"},
{"id":"2","name":"user3","type":"mm","message":"konnichiwa user3"},
{"id":"3","name":"user4","type":"mf","message":"ni hao user4"},
{"id":"4","name":"user5","type":"ff","message":"high 5! user5"}];
var input = 'user5';
var result = $.grep(contentArray, function(e){ return e.name == input; });
The result is an array with the items found. If you know that the object is always there and that it only occurs once, you can just use result[0].id to get the value. Otherwise you should check the length of the resulting array. Example:
if (result.length === 0) {
// not found
} else if (result.length === 1) {
// access the name property using result[0].id
} else {
// multiple items found
}
So you can design a function for above as per your requirement, something like below:
function getID(myArr, inputName) {
var result = $.grep(myArr, function(e){ return e.name == inputName; });
if (result.length === 0) {
return 0;
} else if (result.length === 1) {
return result[0].id
} else {
// multiple items found
// May be it's not true in your case
return result[0].id
}
}