Mongoose adding select prevent returning to client - angularjs

Got the following code:
On AngularJS client:
var getDocs = function() {
return $http.get('/api/docs/list')
.then(function(result) {
return result.data; // bookmark1 line
});
}
On Node.Js BE:
function getDocs() {
return Doc.find({}).exec()
.then(function success(docs) {
return res.send(docs);
});
}
Works perfectly.
When I change the first line in getDocs() to
return Doc.find({}).select('-field1 -field2').exec()
I see the docs after the query execution without the fields (as expected) but for some reason The http is pending and chrome debugger is not stopping on the success callback of the client (bookmark1 line).
Edit:
Changed to
return Cv.find({}).select('-field1 -field2').exec(function success(err, cvs) {
return res.send(cvs);
});
Got the following error in client:
Solution:
Well It turn out I had another field which depends on field1
docSchema.virtual('field3').get(function () {
return this.field1.toString("base64");
});
It fails and for some reason it didnt appear on my IDE.
I Added a null check and that solve the problem.
Not sure if I should remove this question or maybe it has value for other people. Feel free to say what you think.

Related

call on function returns undefined on first call

In my controller i am calling this function in my service. idservice.getid()
I am testing it by printing it to console using console.log(idservice.getid())
and it returns undefined the first time, but after that if i call it again it returns the value.
I understand this is a async issue but im not sure how to make this work.
my service is below:
function idservice (userauth) {
var id;
this.getid = function() {
userauth.currentUser().then(function(user) {
id = user.id;
});
return id
}
}
How can i make it so that on the first call it doesnt return undefined? Is this a async issue?
This's happening because inside userauth currentUser() method you're making http call and response ('user.id') is yet not available. You can return the userauth.currentUser() call inside getid() method & also return id inside its success callback then. So your service method should look like
function idservice (userauth) {
var id;
this.getid = function() {
return userauth.currentUser().then(function(user) {
id = user.id;
return id;
});
}
}
And inside controller you should handle it like
idservice.getid().then(function(response){
$scope.id = response;
});
Here's small example of your requirement: https://plnkr.co/edit/bEjR9e179aRPfJiaQpei?p=preview
I've encountered this problem today, seems like if you request some data from the server and you assign it to a variable THEN you try to print it, it will show undefined on the first call, I think this is not something it should happen since you are trying to print it AFTER you got the information, but whatever.
I fixed it by removing that variable, just got the data then printed it.
I think this will solve your problem (the OP's last login is 2 years ago, but maybe it will help somebody else that encountered this and didn't found a useful answer?)
function idservice (userauth) {
this.getid = function() {
return userauth.currentUser().then(function(user) {
return user.id;
});
}
}
This will return the user.id as it is, it will not store it in a variable, you want it to be stored in a variable ? Store it, but don't print that variable, something like this :
function idservice (userauth) {
var id;
this.getid = function() {
return userauth.currentUser().then(function(user) {
id = user.id;
return user.id;
});
}
}
This worked for me (or at least the logic behind it worked).

kinvey fetching and remove not working (AngularJS)

I have this problem with kinvey backend,
I'm trying to fetch data from my collection but it doesn't work for me. here is my code :
var query = new $kinvey.Query();
query.equalTo('_id', '5909e8084c68b1ef74fa4efc');
var dataStore = $kinvey.DataStore.collection('User1Bases', $kinvey.DataStoreType.Network);
var stream = dataStore.find(query);
stream.subscribe(function onNext(entity) {
// ...
}, function onError(error) {
// ...
}, function onComplete() {
//...
});
Can you help me please
If you let run the code you have posted then consider four things:
Make sure you have Kinvey implemented:
<script src="https://da189i1jfloii.cloudfront.net/js/kinvey-html5-sdk-3.10.2.min.js"></script>
Make sure you have initialized the Kinvey service before:
// Values shown in your Kinvey console
Kinvey.init({
appKey: '<your_appKey>',
appSecret: 'your_appSecret'
});
Make sure you are logged in with a user that has the rights to read your collection (should be fine using the All Users role (default)):
var promise = Kinvey.User.login('<username>', '<password>')
.then(function() {
console.log ("You are logged in");
})
.catch(function(error) {
console.log (error);
});
Output the return result to see whats coming back. To make sure you do the query AFTER successful login, paste you query inside the .then function of login.
I'm not sure if your query is valid unter 3.x since a lot has changed and I'm not working with older Kinvey versions.
So that all together would look like this:
// Initialize Kinvey
Kinvey.init({
appKey: '<your_appKey>',
appSecret: 'your_appSecret'
});
// Login with already registered user
var promise = Kinvey.User.login('<username>', '<password>')
.then(function() {
console.log ("You are logged in");
// Your query
var query = new $kinvey.Query();
query.equalTo('_id', '5909e8084c68b1ef74fa4efc');
var dataStore = $kinvey.DataStore.collection('User1Bases', $kinvey.DataStoreType.Network);
var stream = dataStore.find(query);
stream.subscribe(function onNext(entity) {
// Output of returning result
console.log (entity);
// ...
}, function onError(error) {
// ...
}, function onComplete() {
//...
});
})
.catch(function(error) {
console.log (error);
});
There are now three return sets possible:
Nothing (as you say) -> Something missing/wrong in the code (compare yours with mine)
Empty array: Your query didn't find anything, adapt the search value(s)
One or more entries in the array -> All fine, what you were looking for!
Hope that helps!
When querying by _id there is a built in method: http://devcenter.kinvey.com/angular/guides/datastore#FetchingbyId
Try switching to var stream = dataStore.findById('entity-id');
Also check to make sure you don't have any preFetch or postFetch BL that is interfering with the query.

Is there a timeout event in cucumber-js

I am using cucumber-js to run tests with selenium-webdriver.
I want to add a screenshot capture of the browser when any step times out.
I am using global timeout for all the steps as:
this.setDefaultTimeout(3 * 60 * 1000);
in my hooks file.
How do I register to the global timeout event (if such even exists)?
Selenium Webdriver js do provide function to get screenshot, you just need to use it in After, which is similar to #AfterClass tag in TestNG
The After scenario will execute after every scenario in Feature and check the result of the Scenario, it it is FAILED it will take the screenshot.
The reason for failure can be anything, like a bug, or DEFAULT_TIMEOUT
You need to add this in your world.js
this.After(function (scenario) {
if (scenario.isFailed()) {
// take a screenshot
// driver.takeScreenshot() is defined in webDriver.js
return driver.takeScreenshot()
.then(function (screenShot) {
scenario.attach(new Buffer(screenShot, 'base64'), 'image/png');
return driver.close()
.then(function () {
return driver.quit();
});
});
}
else {
return driver.close()
.then(function () {
return driver.quit();
});
}
});

mapping the response to corresponding request

I am making $http request to multiple environment and processing after I get all the responses. I am using the code below:
$q.all(Object.keys($rootScope.envs).map(request)).then(function(res){
var results = {};
for (var env in res) {
results[env] = res[env].data;
}
}, function(err){
console.error(err);
});
function request(env) {
return $http.get(callService.getDomainUrl()+'/'+$rootScope.envs[env]+ '/hosts.json');
}
The above code works fine, but the results object looks like below:
{
0: {data:{}},
1: {data:{}},
2: {data:{}},
3: {data:{}}
}
I want the corresponding response for each key and the results should be like
{
env1: {data:{//data for env1}},
env2: {data:{//data for env2}},
env3: {data:{//data for env3}},
env4: {data:{//data for env4}},
}
How to map the corresponding response to the key? Please let me know how to get this as this is asynchronous request. Should I have something from the API to know which env the API is coming from?
I think the simplest way would be to push the result handling into the request function, that way you still have the 'env' value in scope.
var results = {};
$q.all(Object.keys($rootScope.envs).map(request)).then(function(res){
// Do something with 'results' here.
}, function(err){
console.error(err);
});
function request(env) {
return $http.get(callService.getDomainUrl()+'/'+$rootScope.envs[env]+ '/hosts.json')
.then(function(res) { results[env] = res.data; return env; });
}
Another option would be to replace my return env with return [env, res.data] and then you can go back to creating the results object as in your original code.
The important thing here is to remember you can handle the $http.get promises individually as well as using the promises from the call to then in $q.all.

Caught in Restangular promises

I've got this code:
var me = Restangular.one('object', 1).get({params:params});
me.then(function (data) {
$scope.me = data;
$scope.loadsubobject();
});
$scope.loadsubobject = function () {
$scope.me.getList("subobject")
.then(function(subobject) {
//the code never gets here
console.log('loaded subobjects', subobjects);
$scope.subobjects = $scope.subobjects.concat(subobject.results);
if (data.next){
$scope.next = data.next;
}
},function(response){
console.log('Error with response:', response.status)
});
when I try to debug the code It seems that after calling the $scope.me.getList("subobject")It returns to the first thenand never getting to the second then, the one that actually process the subobjects I need.
Any clue out of call back hell?
I verified that the server does return the correct answer
How can I fix that? be glad for help with this
turned out to be a completely different issue, the json returned wasn't "flat", so I need to use a responseExtractor as explained here

Resources