on the server is not added "isAdmin" : true, - mongodb

I want to ask you for help.
App running on localhost great.
but on the server is not added "isAdmin" : true, to the mongoDB. When you add admin.
Why? Where is the problem ?
localhost:
{
"_id" : ObjectId("57b174723e755f5dfe36d8b0"),
"salt" : "63855ff664682ad1e8ed77ded97ca5b92da472e9f0f7d68dcb058f35e71d38a4",
"hash" : "03da57be47c9ab1c9657ae9cd5ac3d8b63d56c808e28b51d6f5166bf27d8df99a2e6c25d809fcbd2436b5b883b4a64bd835ea588348d920346d9b3b601c965b90ff23b67687118b56a2b3e35343eb4b693131f7f51f7d1c9bdb4989364477b237f49d496505592564a5c3d88a0b559dc65e5543df06e4c22da50589e6551b69c2406db093a7ef78d31bc8bb8a5423ed4b677913642e0cd335992d222c49e5c58c3450068bd5a2e1cab82a9f73829f695b4686bc76f52c76e0b6ea4f248cb7e8663a96900e5d845773f3a4f09f7988a6ae24fbbdbb0ca7e670a51acd3f9b8c06f533b8c851c40680bd7156d00fe1407acf4879d8095591e8dce3a5379e041a90acb04edecafb38b0093e20db5dc41cd803ae70f351c9e8146d0e959d10114e586a370cd8063e47cc29367af9574e1a20d3973ab4be8d5a16b8a35d89c3534cdf745adfc65cd1d769811a421ea9654884dee289807e518b7eb7ba4c3e5f59242f98df6ccb3f09a9824e8679aec579a8c9a1498fc5819a2e1e8ab2f3cbf866f0e736e5c0b855d9d0f80b462fd50bf7ebf402530aaed84d6f7db5885098124ffa225563517c276563fd7eb3b058cb1f2472896a0b322bdd3b552229a677c45847667b952807ab873e5d2356297514c85cd4c3b3fac3bc3ac16d93033546fa9096e4b738f7eabd1c3494f902d0817b977116f612b3ee9040e0f9cab7e35543a42dc30",
"username" : "mail#gmail.com",
"displayName" : "Admin",
"isAdmin" : true,
"__v" : 0
}
server:
{
"_id" : ObjectId("57b174723e755f5dfe36d8b0"),
"salt" : "63855ff664682ad1e8ed77ded97ca5b92da472e9f0f7d68dcb058f35e71d38a4",
"hash" : "03da57be47c9ab1c9657ae9cd5ac3d8b63d56c808e28b51d6f5166bf27d8df99a2e6c25d809fcbd2436b5b883b4a64bd835ea588348d920346d9b3b601c965b90ff23b67687118b56a2b3e35343eb4b693131f7f51f7d1c9bdb4989364477b237f49d496505592564a5c3d88a0b559dc65e5543df06e4c22da50589e6551b69c2406db093a7ef78d31bc8bb8a5423ed4b677913642e0cd335992d222c49e5c58c3450068bd5a2e1cab82a9f73829f695b4686bc76f52c76e0b6ea4f248cb7e8663a96900e5d845773f3a4f09f7988a6ae24fbbdbb0ca7e670a51acd3f9b8c06f533b8c851c40680bd7156d00fe1407acf4879d8095591e8dce3a5379e041a90acb04edecafb38b0093e20db5dc41cd803ae70f351c9e8146d0e959d10114e586a370cd8063e47cc29367af9574e1a20d3973ab4be8d5a16b8a35d89c3534cdf745adfc65cd1d769811a421ea9654884dee289807e518b7eb7ba4c3e5f59242f98df6ccb3f09a9824e8679aec579a8c9a1498fc5819a2e1e8ab2f3cbf866f0e736e5c0b855d9d0f80b462fd50bf7ebf402530aaed84d6f7db5885098124ffa225563517c276563fd7eb3b058cb1f2472896a0b322bdd3b552229a677c45847667b952807ab873e5d2356297514c85cd4c3b3fac3bc3ac16d93033546fa9096e4b738f7eabd1c3494f902d0817b977116f612b3ee9040e0f9cab7e35543a42dc30",
"username" : "mail#gmail.com",
"displayName" : "Admin",
"__v" : 0
}
Model
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');
var User = new Schema({
username: String,
password: String,
displayName: String,
isAdmin: Boolean
}, {
toObject: { virtuals: true },
toJSON: { virtuals: true }
});
User.virtual("token").set(function(token) {
this._token = token;
}).get(function() { return this._token; });
User.plugin(passportLocalMongoose);
module.exports = mongoose.model("User", User);
RegisterController
app.controller("RegisterController",
[
"$scope", "$location", "Account", "Session",
function($scope, $location, account, session) {
$scope.registerForm = {
name: undefined,
email: undefined,
password: undefined,
confirmPassword: undefined,
errorMessage: undefined
};
$scope.register = function() {
account.register($scope.registerForm.name, $scope.registerForm.email, $scope.registerForm.password, $scope.registerForm.confirmPassword)
.then(function(res) {
session.setUserData(res);
$location.path("/");
}, function(response) {
$scope.registerForm.errorMessage = response.message;
});
};
}
]);
Service session
app.factory("Session", ["$http", function ($http) {
return {
getToken: function() {
var value = sessionStorage.getItem("token");
if (value) return value;
return undefined;
},
getEmail: function() {
var value = sessionStorage.getItem("email");
if (value) return value;
return undefined;
},
getIsAdmin: function() {
var value = sessionStorage.getItem("isAdmin");
if (value) return value == "true";
return undefined;
},
setUserData: function(user) {
sessionStorage.setItem("token", user.token);
sessionStorage.setItem("email", user.username);
$http.defaults.headers.common["Authorization"] = "Bearer " + user.token;
if (user.isAdmin) {
sessionStorage.setItem("isAdmin", "true");
}
},
clear: function() {
sessionStorage.clear();
$http.defaults.headers.common["Authorization"] = undefined;
}
};
}]);

Related

MongoDB data return []

I'm making a project for my college assignment, but I'm having a trouble while i'm trying to get a data from database called 'project' in 'sitelist' collection from MongoDB.
But for some reason the data i got is only an empty array [ ].
I'm new to MongoDB so i want to know where did i do wrong.
server.js
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = express();
const SLDBModel = require('./sldb_schema');
require('./db');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.urlencoded({ extended: true }))
app.use(function (req, res, next)
{
res.setHeader('Access-Control-Allow-Origin','*');
res.setHeader('Access-Control-Allow-Methods','GET, POST, PUT, DELETE');
res.setHeader('Access-Control-Allow-Headers','content-type, x-access-token');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
app.get('/api/getList', function (req, res){
SLDBModel.find({},function(err, data){
if(err){
console.log('//app.get// getList error!...');
res.send(err);
}
else{
console.log(data);
res.send(data.map(v => v.toJSON()));
}
});
});
module.exports = app;
app.listen(3000, ()=>{
console.log("SERVER IS ONLINE! ON PORT 3000");
})
sldb_schema.js
var mongoose = require('mongoose');
const Schema = mongoose.Schema;
const SLSchema = new Schema({
S_NAME: {type: String, required: true},
S_ADD: {type: String, required: true},
S_STATUS: {type: String, required: true}
}
);
const SLDBSchema = new Schema({
list: [SLSchema]
}
);
const SLDBModel = mongoose.model('sitelist', SLDBSchema);
module.exports = SLDBModel;
db.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1/project', {useUnifiedTopology: true, useNewUrlParser: true });
mongoose.connection.on('connected', function () {
console.log('MONGOOSE default connection open');
});
mongoose.connection.on('error', function (err) {
console.log('MONGOOSE default connection error: ' + err);
});
mongoose.connection.on('disconnected', function () {
console.log('MONGOOSE default connection disconnected');
});
process.on('SIGINT', function () {
mongoose.connection.close(function ()
{
console.log('MONGOOSE default connection disconected through app termination');
process.exit(0);
});
});
Data in database called 'project' in collection 'sitelist'
{
"_id" : ObjectId("5ec4672e44f01dcae82c3dde"),
"error" : "0",
"num_rows" : 3,
"list" : [
{
"S_NAME" : "SBOBETH",
"S_ADD" : "sbobeth.com",
"S_STATUS" : "UP"
},
{
"S_NAME" : "GTRCASINO",
"S_ADD" : "gtrcasino.com",
"S_STATUS" : "DOWN"
},
{
"S_NAME" : "SBOBETH",
"S_ADD" : "sbobeth.com",
"S_STATUS" : "DOWN"
},
{
"S_NAME" : "GTRBETCLUB",
"S_ADD" : "gtrbetclub.com",
"S_STATUS" : "UP"
},
{
"S_NAME" : "77UP",
"S_ADD" : "77up.bet.com",
"S_STATUS" : "UP"
},
{
"S_NAME" : "DATABET88",
"S_ADD" : "databet88.net",
"S_STATUS" : "DOWN"
},
{
"S_NAME" : "FAFA855",
"S_ADD" : "fafa855.com",
"S_STATUS" : "UP"
}
]
}
Because your collection's name is not pluralize. Please check answer in below link.
MongoDB and Mongoose: Cannot retrieve data

Parent.save() not working when sub document / deeply nested document is modified

I find my document from whole collection like this:
const account = await Account.findOne({ "buildings.gateways.devices.verificationCode": code })
const buildings = account.buildings
const gateways = buildings[0].gateways;
const devices = gateways[0].devices;
const device = _.filter(devices, d => d.verificationCode === code);
now I want to change one of the property "patientLastName" and then save the whole document. I am doing as below.
device.patientLastName = lastName;
const updated = await account.save();
This simply does not change anything. I have tried many solutions given but none of them working.
not sure if I can save parent document just like that?
I have few other calls where same code works but only change for this is that this is in my post call while working ones are in put call.
My Schema:
const accountSchema = new mongoose.Schema({
email: { type: String, unique: true, required: true },
password: { type: String, required: true },
userName: { type: String, unique: true, required: true },
companyName: { type: String, required: true },
apiKey: { type: String, unique: true, required: true },
apiCallCount: { type: Number, default: 0 },
solutionType: String,
parentCompany: String,
buildings:
[
new mongoose.Schema({
buildingName: String,
address: String,
suite: String,
floor: String,
timeZone: String,
gateways:
[
new mongoose.Schema({
gatewayName: String,
gatewayKey: { type: String, sparse: true },
suite: String,
devices: [
new mongoose.Schema({
serialNumber: { type: String, sparse: true },
area: String,
connectionStatus: Number,
gatewayKey: String,
applicationNumber: Number,
firmwareVersion: String,
needsAttention: Boolean,
verificationCode: String,
patientRiskStatus: String,
patientFirstName: String,
patientLastName: String
}, { timestamps: true })
]
}, { timestamps: true })
]
}, { timestamps: true })
]
}, { timestamps: true });
Update:
I am trying this:
it gives me error message -
"message": "Converting circular structure to JSON"
const updated = account.update(
{
"_id" : ObjectId(accountId),
"buildings.gateways.devices.verificationCode": code
},
{
"$set": {
"buildings.$.gateways.0.devices.0.patientFirstName": "name1",
"buildings.$.gateways.0.devices.0.patientLastName": "name2",
}
}
)
Your help is appreciated. Thanks
UPDATED -
complete call for your reference.
// Register User
loginRouter.post('/register', async (req, res, next) => {
try {
var { email, userName, password, firstName, lastName, role, deviceIds, code } = req.body;
console.log(req.body)
// checking if email or username already exist before registering.
const verifyEmail = await User.find({
$or: [
{ 'email': email },
{ 'userName': userName },
]
})
if (verifyEmail.length > 0) {
throw new BadRequestError('DuplicateEmailOrUserName', {
message: 'Email or Username already exists'
});
}
// finding accountId for verification code first
const account = await Account.findOne({ "buildings.gateways.devices.verificationCode": code })
//console.log(account)
if (account.length === 0) {
console.log("Invalid registration code")
throw new BadRequestError('InvalidVerificationCode', {
message: 'Invalid registration code'
});
}
var accountId = account ? account._id : null
const buildings = account.buildings
const gateways = buildings[0].gateways;
const devices = gateways[0].devices;
//console.log("devices", devices)
// finding deviceId to insert for user from that account
const device = _.filter(devices, d => d.verificationCode === code);
// console.log("device", device)
if (!deviceIds) {
deviceIds = device.map(item => item._id)
// console.log("deviceIds", deviceIds)
}
const hashedPassword = await hasher.hashPassword(password);
const newUser = new User({
accountId: accountId ? accountId : undefined,
userName: userName,
password: hashedPassword,
email: email,
firstName: firstName,
lastName: lastName,
role: role,
refreshToken: uuidv4(),
refreshTokenExpiryDate: moment().add(process.env.REFRESH_TOKEN_EXPIRY_IN_DAYS, 'days'),
deviceIds: deviceIds ? deviceIds : [],
isActive: true,
});
const newlySavedUser = await newUser.save();
const {
refreshToken,
refreshTokenExpiryDate,
password: pwd,
...userWithoutSensitiveInfo
} = newlySavedUser.toObject();
**// solutions by #SuleymanSah** <----
try {
let result = await Account.findByIdAndUpdate(
accountId,
{
$set: {
"buildings.$[building].gateways.$[gateway].devices.$[device].patientFirstName": "userName"
}
},
{
arrayFilters: [
{ "building._id": ObjectId("5d254bb179584ebcbb68b712") },
{ "gateway._id": ObjectId("5d254b64ba574040d9632ada") },
{ "device.verificationCode": "4144" }
],
new: true
}
);
if (!result) return res.status(404);
console.log(result)
//res.send(result);
} catch (err) {
console.log(err);
res.status(500).send("Something went wrong");
}
res.json(newlySavedUser);
next();
} catch (err) {
next(err);
}
});
Let me know if you need more information. Thanks
You can use the filtered positional operator $ for this.
Note that we also need to have the buildingId and gatewayId to make it work dynamically.
router.put("/account/:accountId/:buildingId/:gatewayId", async (req, res) => {
const { patientFirstName, verificationCode } = req.body;
try {
let result = await Account.findByIdAndUpdate(
req.params.accountId,
{
$set: {
"buildings.$[building].gateways.$[gateway].devices.$[device].patientFirstName": patientFirstName
}
},
{
arrayFilters: [
{ "building._id": req.params.buildingId },
{ "gateway._id": req.params.gatewayId },
{ "device.verificationCode": verificationCode }
],
new: true
}
);
if (!result) return res.status(404);
res.send(result);
} catch (err) {
console.log(err);
res.status(500).send("Something went wrong");
}
});
TEST
Let's have this document:
{
"_id" : ObjectId("5e0da052b4b3fe5188602e11"),
"apiCallCount" : 1,
"email" : "abc#def.net",
"password" : "123123",
"userName" : "username",
"companyName" : "companyName",
"apiKey" : "apiKey",
"solutionType" : "solutionType",
"parentCompany" : "parentCompany",
"buildings" : [
{
"_id" : ObjectId("5e0da052b4b3fe5188602e12"),
"buildingName" : "buildingName 1",
"address" : "address",
"suite" : "suite",
"floor" : "floor",
"timeZone" : "String",
"gateways" : [
{
"_id" : ObjectId("5e0da052b4b3fe5188602e13"),
"gatewayName" : "gatewayName 1",
"gatewayKey" : "gatewayKey",
"suite" : "suite",
"devices" : [
{
"_id" : ObjectId("5e0da052b4b3fe5188602e15"),
"serialNumber" : "serialNumber 1",
"area" : "area",
"connectionStatus" : 0,
"gatewayKey" : "gatewayKey",
"applicationNumber" : 11,
"firmwareVersion" : "firmwareVersion",
"needsAttention" : true,
"verificationCode" : "123456",
"patientRiskStatus" : "patientRiskStatus",
"patientFirstName" : "patientFirstName",
"patientLastName" : "patientLastName",
"createdAt" : ISODate("2020-01-02T10:48:34.287+03:00"),
"updatedAt" : ISODate("2020-01-02T10:48:34.287+03:00")
},
{
"_id" : ObjectId("5e0da052b4b3fe5188602e14"),
"serialNumber" : "serialNumber 2",
"area" : "area",
"connectionStatus" : 0,
"gatewayKey" : "gatewayKey",
"applicationNumber" : 22,
"firmwareVersion" : "firmwareVersion",
"needsAttention" : true,
"verificationCode" : "987654",
"patientRiskStatus" : "patientRiskStatus",
"patientFirstName" : "patientFirstName",
"patientLastName" : "patientLastName",
"createdAt" : ISODate("2020-01-02T10:48:34.288+03:00"),
"updatedAt" : ISODate("2020-01-02T10:48:34.288+03:00")
}
],
"createdAt" : ISODate("2020-01-02T10:48:34.288+03:00"),
"updatedAt" : ISODate("2020-01-02T10:48:34.288+03:00")
}
],
"createdAt" : ISODate("2020-01-02T10:48:34.288+03:00"),
"updatedAt" : ISODate("2020-01-02T10:48:34.288+03:00")
}
],
"createdAt" : ISODate("2020-01-02T10:48:34.289+03:00"),
"updatedAt" : ISODate("2020-01-02T10:48:34.289+03:00"),
"__v" : 0
}
To update the device patientFirstName with verificationCode 123456, we need to send a PUT request to the url http://..../account/5e0da052b4b3fe5188602e11/5e0da052b4b3fe5188602e12/5e0da052b4b3fe5188602e13
5e0da052b4b3fe5188602e11 is accountId.
5e0da052b4b3fe5188602e12 is buildingId.
5e0da052b4b3fe5188602e13 is gatewayId.
Request body:
{
"verificationCode": "123456",
"patientFirstName": "UPDATED!!!"
}
Result will be like this:
{
"apiCallCount": 1,
"_id": "5e0da052b4b3fe5188602e11",
"email": "abc#def.net",
"password": "123123",
"userName": "username",
"companyName": "companyName",
"apiKey": "apiKey",
"solutionType": "solutionType",
"parentCompany": "parentCompany",
"buildings": [
{
"gateways": [
{
"devices": [
{
"_id": "5e0da052b4b3fe5188602e15",
"serialNumber": "serialNumber 1",
"area": "area",
"connectionStatus": 0,
"gatewayKey": "gatewayKey",
"applicationNumber": 11,
"firmwareVersion": "firmwareVersion",
"needsAttention": true,
"verificationCode": "123456",
"patientRiskStatus": "patientRiskStatus",
"patientFirstName": "UPDATED!!!",
"patientLastName": "patientLastName",
"createdAt": "2020-01-02T07:48:34.287Z",
"updatedAt": "2020-01-02T07:48:34.287Z"
},
{
"_id": "5e0da052b4b3fe5188602e14",
"serialNumber": "serialNumber 2",
"area": "area",
"connectionStatus": 0,
"gatewayKey": "gatewayKey",
"applicationNumber": 22,
"firmwareVersion": "firmwareVersion",
"needsAttention": true,
"verificationCode": "987654",
"patientRiskStatus": "patientRiskStatus",
"patientFirstName": "patientFirstName",
"patientLastName": "patientLastName",
"createdAt": "2020-01-02T07:48:34.288Z",
"updatedAt": "2020-01-02T07:48:34.288Z"
}
],
"_id": "5e0da052b4b3fe5188602e13",
"gatewayName": "gatewayName 1",
"gatewayKey": "gatewayKey",
"suite": "suite",
"createdAt": "2020-01-02T07:48:34.288Z",
"updatedAt": "2020-01-02T07:48:34.288Z"
}
],
"_id": "5e0da052b4b3fe5188602e12",
"buildingName": "buildingName 1",
"address": "address",
"suite": "suite",
"floor": "floor",
"timeZone": "String",
"createdAt": "2020-01-02T07:48:34.288Z",
"updatedAt": "2020-01-02T07:48:34.288Z"
}
],
"createdAt": "2020-01-02T07:48:34.289Z",
"updatedAt": "2020-01-02T09:10:25.200Z",
"__v": 0
}
And if you always want to update in the first building's in the first gateway, you may use this:
router.put("/account/:accountId", async (req, res) => {
const { patientFirstName, verificationCode } = req.body;
try {
let result = await Account.findByIdAndUpdate(
req.params.accountId,
{
$set: {
"buildings.0.gateways.0.devices.$[device].patientFirstName": patientFirstName
}
},
{
arrayFilters: [{ "device.verificationCode": verificationCode }],
new: true
}
);
if (!result) return res.status(404);
res.send(result);
} catch (err) {
console.log(err);
res.status(500).send("Something went wrong");
}
});
Now you need to send only the accountId in the url like this: http://../account/5e0da052b4b3fe5188602e11

MongoDB putting they key into $set instead of using it for lookup?

I am trying to update a message using userID as my _id
Is splitting it up into findOne - Save - Update the best way?
//
// Find and update message
//
var messageModel = require('../models/messageModel');
var messageTable = mongoose.model('messageModel');
var messageRecord = new messageModel();
var findMessage = () => {
return new Promise((resolve, reject) => {
console.log("=====START findMessage=====")
messageTable.findOne(
{ _id: userID }
,function(err, data) {
if (err) {
reject(new Error('findMessage: ' + err))
return;
}
// Who will have this as unread?
if (userManager==true) {
messageRecord.readUser = false;
messageRecord.readManager = true;
} else {
messageRecord.readUser = true;
messageRecord.readManager = false;
}
// If message not found, then create new one
if (!data) {
console.log("=====CREATE NEW RECORD=====")
messageRecord._id = userID;
messageRecord.activityDate = Math.round(new Date().getTime()/1000);
messageRecord.messages = {
"message" : message,
"date" : Math.round(new Date().getTime()/1000),
"property" : propertyID,
"booking" : bookingID,
"manager" : userManager
}
messageRecord.save(function (err, res) {
if (err) {
reject(new Error('findMessage: ' + err));
return;
}
})
console.log("=====RESOLVE findMessage=====")
resolve();
return;
}
// If message found, then add message
console.log("=====ADD LINE TO RECORD=====")
messageTable.update (
{ _id: userID },
{
$set: {
activityDate : Math.round(new Date().getTime()/1000),
readUser : messageRecord.readUser,
readManager : messageRecord.readManager
},
$push: {
messages: {
"message" : message,
"date" : Math.round(new Date().getTime()/1000),
"property" : propertyID,
"booking" : bookingID,
"manager" : userManager
}
}
},
{ upsert: true }
).exec(function (err, res) {
if (err) {
reject(new Error('findMessage: ' + err));
return;
}
})
console.log("=====RESOLVE findMessage=====")
resolve();
return;
});
})};
Do I need to put upsert:true? (what ever that means)
Or should I use findOneAndUpdate?
And would you use findOneAndUpdate or just update? And why?
I tought it went like this:
findone
if not found then save
if found then update
UPDATE - Thanks to lascot I ended up doing this, and it works great!
// Save message
messageTable.update (
{ _id: userID },
{
$setOnInsert: {
_id: userID
},
$set: {
activityDate : Math.round(new Date().getTime()/1000),
readUser : messageRecord.readUser,
readManager : messageRecord.readManager
},
$push: {
messages: {
"message" : message,
"date" : Math.round(new Date().getTime()/1000),
"property" : propertyID,
"booking" : bookingID,
"manager" : userManager
}
}
},
{ upsert: true }
).exec(function (err, res) {
if (err) {
reject(new Error('findMessage: ' + err));
return;
}
})

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();
};
});

Setting params in Kendo UI Grid when calling a rest service [Workaround]

I have a Kendo UI Grid that is calling a rest service. It works fine, as long as I do not try to use any params.
I know the the rest service is correct, as I can call it from a browser, and get correct results [depending on the param I send]. Also, when I look the server log I see that it is calling the rest service with no params.
My code is below:
document).ready( function() {
var crudServiceBaseUrl = "rsPC.xsp",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/PCByStatus",
filter: {field: "status", value: "2" }
dataType: "json",
update: {
url: crudServiceBaseUrl + "/PC/Update",
dataType: "json"
},
destroy: {
url: crudServiceBaseUrl + "/PC/Destroy",
dataType: "json"
},
create: {
url: crudServiceBaseUrl + "/PC/Create",
dataType: "json"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
batch: true,
pageSize: 20,
scrollable: {
virtual: true
},
height: 543,
schema: {
model: {
id: "PCId",
fields: {
PCId: {type:"string"},
serialNumber: {type: "string"},
officeLoc: {type: "string"},
unid: {type:"string"},
model: {type:"string"},
checkInDate: {type: "string"}
}
}
}
});
// Grid
grid = $("#grid").kendoGrid( {
dataSource: dataSource,
columns : [ {
field : "serialNumber",
title : "Serial Number"
}, {
field : "model",
title : "Model"
}, {
field : "officeLoc",
title : "Office Location"
}, {
field : "checkInDate",
title : "Check In Date",
template: "#= kendo.toString(kendo.parseDate(checkInDate, 'yyyy-MM-dd'), 'MM/dd/yyyy') #"
} ],
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
dataBound : addExtraStylingToGrid,
reorderable : true,
filterable : true,
scrollable : true,
selectable : true,
sortable : true,
});
I still cannot get this to work and am a bit stumped.
I have two rest services, one returns all data, one takes "status" as a part and return a subset of the data that equals the parm.
The URL is:
http://localhost/scoApps/PC/PCApp.nsf/rsPC.xsp/PCByStatus?status=2
When entered into browser I get the correct number of records.
So I changed the code (see below). I have included all of the code for the CSJS:
$(document).ready( function() {
// Double Click On row
$("#grid").on(
"dblclick",
" tbody > tr",
function() {
var grid = $("#grid").data("kendoGrid");
var row = grid.dataItem($(this));
window.location.replace("xpFormPC.xsp" + "?key=" + row.unid + "target=_self");
});
// Add hover effect
addExtraStylingToGrid = function() {
$("table.k-focusable tbody tr ").hover( function() {
$(this).toggleClass("k-state-hover");
});
};
// Search
$("#search").keyup( function() {
var val = $('#search').val();
$("#grid").data("kendoGrid").dataSource.filter( {
logic : "or",
filters : [ {
field : "serialNumber",
operator : "contains",
value : val
}, {
field : "officeLoc",
operator : "contains",
value : val
}, {
field : "model",
operator : "contains",
value : val
} ]
});
});
var crudServiceBaseUrl = "rsPC.xsp",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/PCByStatus",
dataType: "json"
},
update: {
url: crudServiceBaseUrl + "/PC/Update",
dataType: "json"
},
destroy: {
url: crudServiceBaseUrl + "/PC/Destroy",
dataType: "json"
},
create: {
url: crudServiceBaseUrl + "/PC/Create",
dataType: "json"
},
parameterMap: function(options, operation) {
if (operation == "read"){
options.field = "status"
options.value = "2"
return options;
}
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
batch: true,
pageSize: 20,
scrollable: {
virtual: true
},
height: 543,
schema: {
model: {
id: "PCId",
fields: {
PCId: {type:"string"},
serialNumber: {type: "string"},
officeLoc: {type: "string"},
unid: {type:"string"},
model: {type:"string"},
checkInDate: {type: "string"}
}
}
}
});
// Grid
grid = $("#grid").kendoGrid( {
dataSource: dataSource,
columns : [ {
field : "serialNumber",
title : "Serial Number"
}, {
field : "model",
title : "Model"
}, {
field : "officeLoc",
title : "Office Location"
}, {
field : "checkInDate",
title : "Check In Date",
template: "#= kendo.toString(kendo.parseDate(checkInDate, 'yyyy-MM-dd'), 'MM/dd/yyyy') #"
} ],
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
dataBound : addExtraStylingToGrid,
reorderable : true,
filterable : true,
scrollable : true,
selectable : true,
sortable : true
});
// Edit
function onEdit(e) {
}
// Change
function onChange(args) {
var model = this.dataItem(this.select());
ID = model.ID;
}
;
});
What am I doing wrong?
=========================================
I have a workaround. Or possibly this is the way it is supposed to be done.
var crudServiceBaseUrl = "rsPC.xsp", dataSource = new kendo.data.DataSource(
{
transport : {
read : {
url : crudServiceBaseUrl
+ "/PCByStatus?status=2",
dataType : "json"
},
Now I just construct the URL I want. Not so elegant I suppose, but it works.
I have a workaround. Or possibly this is the way it is supposed to be done.
var crudServiceBaseUrl = "rsPC.xsp", dataSource = new kendo.data.DataSource(
{
transport : {
read : {
url : crudServiceBaseUrl
+ "/PCByStatus?status=2",
dataType : "json"
},
Filter is used for client side data unless you set serverFiltering to true.
Here is the filter kendo documentation and the serverFiltering documentation.
I use parameterMap when I need to send parameters that are not created by filtering the control that I'm using. The kendo documentation provides an example using parameterMap.
Here is an example of how I've used it in the past:
var appsDataSource = new kendo.data.DataSource({
transport: {
read: {
url: apiUrl + "App"
},
parameterMap: function (data, action) {
if (action === "read") {
data.lobid = lobId;
data.parent = isParent;
return data;
} else {
return data;
}
}
}
});
Try changing the parameterMap:
parameterMap: function(options, operation) {
if (operation == "read"){
options.field = "status";
options.value = "2";
return options;
}
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
and update the read definition to remove filter. One thing to consider is that you are not returning anything from the read method if it doesn't meet the criteria of not being a read and options is not null. That leaves out any other combination that isn't obviously handled in your existing code.