How save changes with Ext.data.HttpProxy? - extjs3

I have:
var writer = new Ext.data.JsonWriter({
encode: true,
writeAllFields: false
});
var reader = new Ext.data.JsonReader({
idProperty: 'id',
root: 'data',
}, [
{name: 'id'},
{name: 'status'},
{name: 'login'},
{name: 'fio'},
{name: 'description'},
{name: 'create_date'}
]);
var proxy = new Ext.data.HttpProxy({
api: {
read : '/test/read.php',
create : '/test/create.php',
update : '/test/update.php',
destroy : '/test/destroy.php'
}
});
var store = new Ext.data.Store({
proxy: proxy,
reader: reader,
writer: writer,
autoLoad: true,
autoSave: false
});
I need php example for httpproxy create or update or destroy, i dont undestand how save all with php(send parameters?)?
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

I do like this:
proxy.on('beforewrite', function(proxy, action, rec) {
if (action=='update') {
if (!rec.length) {
var record = new Array(rec);
}else{
var record = rec;
}
for (var i=0; i<record.length; i++) //>
{
xmlhttp.open('GET', '/test/dtp_users.php?level=1&id='+record[i].get('id')+'&status='+record[i].get('status')+'&login='+record[i].get('login')+'&fio='+record[i].get('fio')+'&description='+record[i].get$
xmlhttp.send(null);
if(xmlhttp.status == 200) {
Ext.Msg.alert('Статус сохранения',xmlhttp.responseText);
};
};
};
if (action=='destroy') {
if (!rec.length) {
var record = new Array(rec);
}else{
var record = rec;
}
for (var i=0; i<record.length; i++) //>
{
xmlhttp.open('GET', '/test/dtp_users.php?level=2&id='+record[i].get('id')+'&status='+record[i].get('status')+'&login='+record[i].get('login')+'&fio='+record[i].get('fio')+'&description='+record[i].get$
xmlhttp.send(null);
if(xmlhttp.status == 200) {
Ext.Msg.alert('Статус сохранения',xmlhttp.responseText);
};
};
};
if (action=='create') {
if (!rec.length) {
var record = new Array(rec);
}else{
var record = rec;
}
for (var i=0; i<record.length; i++) //>
{
xmlhttp.open('GET', '/test/dtp_users.php?level=3&id='+record[i].get('id')+'&status='+record[i].get('status')+'&login='+record[i].get('login')+'&fio='+record[i].get('fio')+'&description='+record[i].get$
xmlhttp.send(null);
if(xmlhttp.status == 200) {
Ext.Msg.alert('Статус сохранения',xmlhttp.responseText);
};
};
};
});
and it working.

Related

How can I pass a variable in sort funtcion of mongobd?

I want to pass this name variable in sort function. I am getting the value of name in console.log but its not working in sort function.
var coldata = req.body.order[0].column;
var name = req.body.columns[coldata].data; // Want to pass this variable in sort()
var first = req.body.order[0].dir;
var last = req.body.order[0].dir;
var x,y;
if (first == 'asc'){
x = 1
}else{
x = -1;
}
if (last == 'asc'){
y = 1
}else{
y = -1;
}
var searchStr = req.body.search.value;
if(req.body.search.value)
{
var regex = new RegExp(req.body.search.value, "i")
searchStr = { $or: [{'firstname':regex },{'lastname': regex}] };
}
else
{
searchStr={};
}
console.log(req.body.search.value)
var recordsTotal = 0;
var recordsFiltered=0;
console.log(searchStr);
db.count({}, function(err, c) {
recordsTotal=c;
db.count(searchStr, function(err, c) {
recordsFiltered=c;
db.find(searchStr, 'firstname lastname',{'skip': Number( req.body.start), 'limit': Number(req.body.length) }, function (err, results) {
if (err) {
console.log('error while getting results'+err);
return;
}
var data = JSON.stringify({
"draw": req.body.draw,
"recordsFiltered": recordsFiltered,
"recordsTotal": recordsTotal,
"data": results
});
res.send(data);
}).sort({name:x});// Not getting value of name here
});
});
});
You can use an aggregation pipeline
const sort = {};
sort[name] = x
const pipeline = [
{ $match: searchStr },
{ $skip: Number( req.body.start) },
{ $limit: Number( req.body.length) },
{ $sort: sort }
];
db.aggregate(pipeline) ...

Getting an avarage value from MongoDB

I have this mongoose model:
var juomaSchema = new mongoose.Schema({
...
valikoima: String,
img: String,
views: {default: 0, type: Number},
rating: [],
...
});
juomaSchema.methods.getAvarageRating = function() {
if (this.rating.length !== 0) {
var totalScore = 0;
this.rating.forEach(function(drinkRating) {
totalScore += drinkRating
});
return totalScore/this.rating.length;
} else {
return 0;
}
};
My problem is, that I need to sort a query by the avarage rating of the rating field.
I already have the method in the model, but I can't seem to use a function inside a sort query.
Here's my sort:
router.get("/oluet", function(req, res) {
var perPage = 20,
page = req.query.page,
sortBy = req.query.sort,
asc = req.query.asc;
var sort = {[sortBy] : asc};
console.log(sort);
if(req.xhr) {
//Sanitazes input
const regex = new RegExp(escapeRegExp(req.query.search), "gi");
Juoma.find({nimi: regex, tyyppi: "oluet"})
.sort(sort)
.limit(perPage)
.skip(perPage * page)
.exec(function(err, drinks) {
How would I do this? Making two fields: totalRating and timesRates, and doing some aggregation magic?
Felix solved this in the comments with
{
$project: {
avg: {$avg: "$rating"}
}
}

TypeError: Cannot read property ‘uid’ of undefined ionic-v1

I have the following question as to how I could be solving this problem with the property uid with authentication via facebook / firebase. This displays the error message in the command prompt according to the image.
Print Error Prompt
Services
'use strict';
app.factory('Auth', function ($firebaseAuth, $firebaseObject, $firebaseArray, $state, $http, $q, $cordovaOauth) {
var ref = firebase.database().ref();
var auth = $firebaseAuth();
var Auth = {
createProfile: function(uid, profile) {
return ref.child('profiles').child(uid).set(profile);
},
getProfile: function(uid) {
return $firebaseObject(ref.child('profiles').child(uid));
},
login: function() {
var provider = new firebase.auth.FacebookAuthProvider();
provider.addScope('public_profile, email, user_location, user_birthday, user_photos, user_about_me');
// return auth.$signInWithPopup(provider)
// .then(function(result) {
$cordovaOauth.facebook("1455510817798096", ["public_profile", "email", "user_location", "user_birthday", "user_photos", "user_about_me"])
.then(function (result) {
//var accessToken = result.credential.accessToken;
var user = Auth.getProfile(result.user.uid).$loaded();
//ver ideia do tairone pra ver o que acontece
// var user = Auth.getProfile(result.user).$loaded();
user.then(function(profile) {
if (profile.name == undefined) {
var genderPromise = $http.get('https://graph.facebook.com/me?fields=gender&access_token=' + accessToken);
var birthdayPromise = $http.get('https://graph.facebook.com/me?fields=birthday&access_token=' + accessToken);
var locationPromise = $http.get('https://graph.facebook.com/me?fields=location&access_token=' + accessToken);
var bioPromise = $http.get('https://graph.facebook.com/me?fields=about&access_token=' + accessToken);
var imagesPromise = $http.get('https://graph.facebook.com/me/photos/uploaded?fields=source&access_token=' + accessToken);
var promises = [genderPromise, birthdayPromise, locationPromise, bioPromise, imagesPromise];
$q.all(promises).then(function(data) {
var info = result.user.providerData[0];
var profile = {
name: info.displayName,
email: info.email,
avatar: info.photoURL,
gender: data[0].data.gender ? data[0].data.gender : "",
birthday: data[1].data.birthday ? data[1].data.birthday : "",
age: data[1].data.birthday ? Auth.getAge(data[1].data.birthday) : "",
location: data[2].data.location ? data[2].data.location.name : "",
bio: data[3].data.about ? data[3].data.about : "",
images: data[4].data.data
}
Auth.createProfile(result.user.uid, profile);
//mudar a profile tambem mudando ideia tairone
//Auth.createProfile(result.user, profile);
});
}
});
});
},
logout: function() {
return auth.$signOut();
},
getAbout: function(access_token) {
return $http.get('https://graph.facebook.com/me?fields=bio&access_token=' + access_token);
},
getAge: function(birthday) {
return new Date().getFullYear() - new Date(birthday).getFullYear();
},
requireAuth: function() {
return auth.$requireSignIn();
},
getProfilesByAge: function(age) {
return $firebaseArray(ref.child('profiles').orderByChild('age').startAt(18).endAt(age));
},
getProfiles: function(){
return $firebaseArray(ref.child('profiles'));
}
};
auth.$onAuthStateChanged(function(authData) {
if(authData) {
console.log('Este usuario ja se encontra logado!');
} else {
$state.go('login');
console.log('Este usuario ainda nao se encontra logado no aplicativo da cleo.');
}
});
return Auth;
});
Controller
'use strict';
app.controller('AuthCtrl', function(Auth, $state) {
var auth = this;
auth.login = function() {
console.log('Usuario clicou no botao para realizar login!');
// return Auth.login().then(function(user) {
return Auth.login(function(user) {
$state.go('app.home');
});
};
auth.logout = function() {
Auth.logout();
};
});

How can I find documents in a collection based on array values

I tried adding a helper to return array with documents, which looks like:
documents = {
realPlayers: [],
subscribers: [
{playerId: },
{playerId: },
{playerId: }
],
privatGame:,
gameType:,
gameStatus: 'active'
}
I tried this, but it doesn't work (forEach too):
Template.myGames.helpers({
'myGames': function() {
let gamePul = [],
activeGames = Games.find({gameStatus: "active"});
for (var i = 0; i < activeGame.length; i++) {
if (activeGame[i].subscribers) {
for (var j = 0; j < activeGame[i].subscribers.length; j++) {
if (activeGame[i].subscribers[j].playerId = Meteor.userId()) gamePul.push(activeGame[i]);
}
}
};
return gamePul;
}
});
You're just trying to find the set of games the current user is a subscriber to right? You just need $elemMatch in your query:
Template.myGames.helpers({
myGames: function() {
return Games.find({ gameStatus: "active",
subscribers: { $elemMatch: { playerId: Meteor.userId() }}});
}
});
docs

ng-repeat showing functions names and data

I'm a beginner with angularjs and mongolab ..
I have this code, to edit a record in mongolab :
function EditCtrl($scope, $location, $routeParams, Project) {
var self = this;
Project.get({id: $routeParams.projetId}, function(projet) {
self.original = projet;
$scope.projet = new Project(self.original);
});
$scope.save = function() {
$scope.projet.update(function() {
$location.path('/list');
});
};
}
It works perfectly.
I wanted to display all the keys and values from the record, this is the code :
<div ng-repeat="(key, val) in projet">
<div>{{key}}:{{val}}</div>
</div>
And this is the result :
_id:{}
destroy:
name:Test test
rang:4
update:
In my record, i only have the _id, name and rang. I don't know why "destroy:" dans "update:" are displayed! probably because i use this code to connect to mongolab :
angular.module('mongolab', ['ngResource']).
factory('Project', function($resource) {
var Project = $resource('https://api.mongolab.com/api/1/databases' +
'/_____/collections/_________/:id',
{apiKey: '___________________'}, {
update: {method: 'PUT'}
}
);
Project.prototype.update = function(cb) {
return Project.update({id: this._id.$oid},
angular.extend({}, this, {_id: undefined}), cb);
};
Project.prototype.destroy = function(cb) {
return Project.remove({id: this._id.$oid}, cb);
};
return Project;
});
What should i do to only display the record data ?
thanks
Return a service and pass the item you receive from get() back to update and destroy.
factory('Project', function($resource) {
return {
get: function() {
return $resource('https://api.mongolab.com/api/1/databases' +
'/_____/collections/_________/:id',
{apiKey: '___________________'}, {
update: {method: 'PUT'}
},
update : function(itm, cb) {
return item.update({id: item._id.$oid},
angular.extend({}, item, {_id: undefined}), cb);
},
destroy : function(item, cb) {
return item.remove({id: item._id.$oid}, cb);
};
Otherwise you can instantiate only one and reference it
factory('Project', function($resource) {
var item =$resource('https://api.mongolab.com/api/1/databases' +
'/_____/collections/_________/:id',
{apiKey: '___________________'}, {
update: {method: 'PUT'}
return {
update : function(cb) {
return item.update({id: item._id.$oid},
angular.extend({}, item, {_id: undefined}), cb);
},
destroy : function(cb) {
return item.remove({id: item._id.$oid}, cb);
};