Saving data for only one user with using Firebase - javascript

I'm developing electron app and using Firebase Database. I created database user by user but saving data for everyone. I want to save data also separate for the user ID.
I can create a user under their user IDs but cannot write their data under their user IDs.
app.controller('loginCtrl', function($scope,$location){
$scope.signup = function(){
auth.createUserWithEmailAndPassword($scope.mail,$scope.parola).then(sonuc=>{
console.log(sonuc.user);
return db.collection('users').doc(sonuc.user.uid).set({
inputQ: $scope.inputQ
}).then( ()=> {
console.log('deneme basarili');
}).catch(err => {
console.log(err.message);
})
})
}
$scope.login = function(){
auth.signInWithEmailAndPassword($scope.mail,$scope.parola).then(sonuc=> {
$location.path('/dashboard')
})
}
});
This part successfully creates a user under its user ID.
app.controller('dashboardCtrl', function($scope){
$scope.add = function() {
db.collection('users').doc(user.uid).add({
baslik: $scope.baslik,
icerik: $scope.icerik
}).then( ()=> {
console.log('ekleme basarili');
}).catch(err=>{
console.log(err.message);
})
}
This part cannot create data under its user ID.
The error is user is not defined.

app.controller('dashboardCtrl', function($scope){
$scope.add = function() {
db.collection('users').doc(user.uid).set({
baslik: $scope.baslik,
icerik: $scope.icerik
}).then( ()=> {
console.log('ekleme basarili');
}).catch(err=>{
console.log(err.message);
})
}
Trying using "set" rather than "add", "add" is usually reserved for adding to a collection where it creates the records identifier for you, without you having to provide it.

You should change .add to .set but also make sure to include merge: true to prevent an override to the document (e.x. if there is a current document it will update it and if there is no document it will create one).
app.controller('dashboardCtrl', function($scope){
$scope.add = function() {
db.collection('users').doc(user.uid).set(
{
.
.
.
},
{ merge: true }
).then( ()=> {
}).catch(err=>{
})
}

Related

$log anonymous function angular js not working

I have a problem when I try to log some data inside the function of webtorrent.
I want to log some values of this.client.add but I don't have access.
Some idea of what's going on here?
import Webtorrent from 'webtorrent';
class PlaylistController {
/** #ngInject */
constructor($http, $log) {
this.log = $log;
this.client = new Webtorrent();
$http
.get('app/playlist/playlist.json')
.then(response => {
this.Torrent = response.data;
});
}
addTorrent(magnetUri) {
this.log.log(magnetUri);
this.client.add(magnetUri, function (torrent) {
// Got torrent metadata!
this.log.log('Client is downloading:', torrent.infoHash);
torrent.files.forEach(file => {
this.log(file);
});
});
this.log.log('sda');
this.log.log(this.client);
}
}
export const playlist = {
templateUrl: "app/playlist/playlist.html",
controller: PlaylistController,
bindings: {
playlist: '<'
}
};
Another thing its I use yeoman for the scaffold of my app and its has JSLint with console.log forbidden and its said that you must use angular.$log, but the thing its I don't wanna change that, I wanna understand the problem here.
You either need to refer to this (the class) as another variable to use inside the function(torrent) function or use arrow functions so that this reference remains the class one.
Solution 1, using another variable to ref the class:
addTorrent(magnetUri) {
this.log.log(magnetUri);
var that = this;
this.client.add(magnetUri, function (torrent) {
// Got torrent metadata!
that.log.log('Client is downloading:', torrent.infoHash);
torrent.files.forEach(file => {
that.log(file);
});
});
this.log.log('sda');
this.log.log(this.client);
}
Solution 2, using arrow functions:
addTorrent(magnetUri) {
this.log.log(magnetUri);
this.client.add(magnetUri, torrent => {
// Got torrent metadata!
this.log.log('Client is downloading:', torrent.infoHash);
torrent.files.forEach(file => {
this.log(file);
});
});
this.log.log('sda');
this.log.log(this.client);
}

BookhshelfJS: Attaching One-to-One relationship

I have two tables, User and Address. My table User has two methods:
shippingAddress: function() {
var Address = require(appRoot + '/config/db').model('Address');
return this.belongsTo(Address, 'shipping_address_id');
},
billingAddress: function() {
var Address = require(appRoot + '/config/db').model('Address');
return this.belongsTo(Address, 'billing_address_id');
}
How can I attach an Address to say my shippingAddress? I tried the following:
new Address(addressQuery)
.fetch()
.then(function (address) {
new User(userQuery)
.fetch()
.then(function (user) {
// Nothing here works
// I tried the following:
user.shippingAddress().attach(address); // Attach is not defined
user.shippingAddress().sync(address); // Nothing happens
user.shippingAddress().set(address); // Nothing happens
user.save();
});
});
The only thing I can do is:
user.attributes.shipping_address_id = address.id;
user.save();
Which is not a very elegant solution. What am I doing wrong?
First, set the list of relations with "withRelated"
new User(userQuery)
.fetch({
withRelated:['shippingAddress']
})
.then(function (user) {
Then you're able to do:
user.related('shippingAddress').set(...).save();
Be sure shippingAddress() isn't a 'static' function within your User model

How do you save new users in AngularFire?

I'm trying to create users via the $createUser method which is part of the firebase simple login service.
The AngularFire/Firebase documentation discusses adding additional data to a user object -- username, etc. -- but I'm confused as to how to save the user created with $createUser to Firebase itself as
{
"users": {
"simplelogin:1": {
"provider": "password",
"email": "something#some.com"
"provider_id": "1"
},
}
}
My Firebase is currently completely empty and I'm trying to use the below controller code to create a new user.
app.controller('MainCtrl', ['$scope', '$firebase', '$firebaseSimpleLogin',
function ($scope, $firebase, $firebaseSimpleLogin) {
var ref = new Firebase('https://socialfiction.firebaseio.com/');
var sync = $firebase(ref);
$scope.auth = $firebaseSimpleLogin(ref);
var currentUser = $scope.auth.$getCurrentUser().then(function(user, err) {
if (err) {
console.log(err);
}else{
console.log(user);
return user;
}
});
$scope.createUser = function() {
$scope.auth.$createUser('jamie.smith#email.com', 'password').then(function(user) {
sync.child('users').child(user.uid).$set({
// not sure if this is right?
});
});
}
}
]);
I guess my question specifically is what do I need to add to my $scope.createUser function to properly $set the new user to a users object inside of my firebase?

Track and count clicks with AngularJS and post to MongoDB

I want to be able to track the click from a user on an item and have it update the JSON object associate with it and display the number of all the clicks. I know how to create and delete an object, but how do I add a new name and value and update the object when the user clicks and appropriate vote button? Any help will be greatly appreciated and I thank you in advance.
The HTML
<body ng-controller="mainController">
<div class="table-responsive">
<table class="table">
<tr>
<td>Vote</td>
<td>Song</td>
<td>Edit</td>
</tr>
<tr ng-repeat="todo in todos">
<td><button class="btn btn-success icon-thumbs-up" alt="Up vote this song if you like it.">Vote</button></td>
<td>{{ todo.text }}</td>
<td><button class="btn btn-danger fa fa-times" ng-click="deleteTodo(todo._id)" alt="Remove the song if you need to make an edit and then add it back."></button></td>
</tr>
</table>
</div>
</body>
The Model
var mongoose = require('mongoose');
module.exports = mongoose.model('Todo', {
text : String,
done : Boolean
});
The Service
angular.module('todoService', [])
// super simple service
// each function returns a promise object
.factory('Todos', function($http) {
return {
get : function() {
return $http.get('/api/todos');
},
create : function(todoData) {
return $http.post('/api/todos', todoData);
},
delete : function(id) {
return $http.delete('/api/todos/' + id);
}
}
});
Server side Angular
var Todo = require('./models/todo');
module.exports = function(app) {
// api ---------------------------------------------------------------------
// get all todos
app.get('/api/todos', function(req, res) {
// use mongoose to get all todos in the database
Todo.find(function(err, todos) {
// if there is an error retrieving, send the error. nothing after res.send(err) will execute
if (err)
res.send(err)
res.json(todos); // return all todos in JSON format
});
});
// create todo and send back all todos after creation
app.post('/api/todos', function(req, res) {
// create a todo, information comes from AJAX request from Angular
Todo.create({
text : req.body.text,
done : false
}, function(err, todo) {
if (err)
res.send(err);
// get and return all the todos after you create another
Todo.find(function(err, todos) {
if (err)
res.send(err)
res.json(todos);
});
});
});
// delete a todo
app.delete('/api/todos/:todo_id', function(req, res) {
Todo.remove({
_id : req.params.todo_id
}, function(err, todo) {
if (err)
res.send(err);
// get and return all the todos after you create another
Todo.find(function(err, todos) {
if (err)
res.send(err)
res.json(todos);
});
});
});
// application -------------------------------------------------------------
app.get('*', function(req, res) {
res.sendfile('./public/index.html'); // load the single view file (angular will handle the page changes on the front-end)
});
};
Client side Angular
angular.module('todoController', [])
// inject the Todo service factory into our controller
.controller('mainController', function($scope, $http, Todos) {
$scope.formData = {};
$scope.loading = true;
// GET =====================================================================
// when landing on the page, get all todos and show them
// use the service to get all the todos
Todos.get()
.success(function(data) {
$scope.todos = data;
$scope.loading = false;
});
// CREATE ==================================================================
// when submitting the add form, send the text to the node API
$scope.createTodo = function() {
$scope.loading = true;
if ($scope.formData.text != undefined) {
// call the create function from our service (returns a promise object)
Todos.create($scope.formData)
// if successful creation, call our get function to get all the new todos
.success(function(data) {
$scope.loading = false;
$scope.formData = {}; // clear the form so our user is ready to enter another
$scope.todos.unshift(data); // assign our new list of todos
});
}
};
// DELETE ==================================================================
// delete a todo after checking it
$scope.deleteTodo = function(id) {
$scope.loading = true;
Todos.delete(id)
// if successful creation, call our get function to get all the new todos
.success(function(data) {
$scope.loading = false;
$scope.todos = data; // assign our new list of todos
});
};
});
Here is what you would do.
Add a new field to schema to store the votes:
votes: {type: Number, default: 0}
Add a new handler on the server side to increment vote when it gets a request:
app.get('/api/todos/:todo_id/vote', function(req, res) {
Todo.update({_id: req.params.todo_id}, { $inc: {votes: 1} } ), function(err,doc){
...
}
}
Add a new function to AngularJS service to call this new API handler:
vote: function(id) {
return $http.get('/api/todos/' + id + '/vote');
}
Wire up ngClick on ngRepeated elements to call the new Svc function. NOTE: You would need Todos svc in your scope to do this as below, otherwise create a wrapper function in the scope as you have done.
<td>
<button data-ng-click="Todos.vote(todo._id)"
class="btn.." alt="Up vote this....">Vote
</button>
</td>
then display in your view somehow the new "votes" field of the ToDo Models coming back.
Check this out: http://meanjs.org/ You can get a lot of good examples working with Angular, node and Mongo, look at the "articles" module that comes with it.
I didn't try any of this but it should give you the basic idea what to do. Also, realize there is nothing here to stop a user from upvoting more than once. Hope it helps!

AngularJS redirection after ng-click

I have a REST API that read/save data from a MongoDB database.
The application I use retrieves a form and create an object (a job) from it, then save it to the DB. After the form, I have a button which click event triggers the saving function of my controller, then redirects to another url.
Once I click on the button, I am said that the job has well been added to the DB but the application is jammed and the redirection is never called. However, if I reload my application, I can see that the new "job" has well been added to the DB. What's wrong with this ??? Thanks !
Here is my code:
Sample html(jade) code:
button.btn.btn-large.btn-primary(type='submit', ng:click="save()") Create
Controller of the angular module:
function myJobOfferListCtrl($scope, $location, myJobs) {
$scope.save = function() {
var newJob = new myJobs($scope.job);
newJob.$save(function(err) {
if(err)
console.log('Impossible to create new job');
else {
console.log('Ready to redirect');
$location.path('/offers');
}
});
};
}
Configuration of the angular module:
var myApp = angular.module('appProfile', ['ngResource']);
myApp.factory('myJobs',['$resource', function($resource) {
return $resource('/api/allMyPostedJobs',
{},
{
save: {
method: 'POST'
}
});
}]);
The routing in my nodejs application :
app.post('/job', pass.ensureAuthenticated, jobOffers_routes.create);
And finally the controller of my REST API:
exports.create = function(req, res) {
var user = req.user;
var job = new Job({ user: user,
title: req.body.title,
description: req.body.description,
salary: req.body.salary,
dueDate: new Date(req.body.dueDate),
category: req.body.category});
job.save(function(err) {
if(err) {
console.log(err);
res.redirect('/home');
}
else {
console.log('New job for user: ' + user.username + " has been posted."); //<--- Message displayed in the log
//res.redirect('/offers'); //<---- triggered but never render
res.send(JSON.stringify(job));
}
});
};
I finally found the solution ! The issue was somewhere 18inches behind the screen....
I modified the angular application controller like this :
$scope.save = function() {
var newJob = new myJobs($scope.job);
newJob.$save(function(job) {
if(!job) {
$log.log('Impossible to create new job');
}
else {
$window.location.href = '/offers';
}
});
};
The trick is that my REST api returned the created job as a json object, and I was dealing with it like it were an error ! So, each time I created a job object, I was returned a json object, and as it was non null, the log message was triggered and I was never redirected.
Furthermore, I now use the $window.location.href property to fully reload the page.

Categories

Resources