Searching mongodb with mongoose inside AngularJS app - angularjs

Hello everyone am trying to search (query) the mongodb using mongoose in my AngularJS app. Am looking to have specific element. Can you help ? Any suggestion would make me advance. I need the general idea. Also I am new to mean
here is my angular code :
var app = angular.module('chirpApp', ['ngRoute', 'ngResource']).run(function($rootScope, $http) {
$rootScope.authenticated = false;
$rootScope.current_user = '';
$rootScope.signout = function(){
$http.get('auth/signout');
$rootScope.authenticated = false;
$rootScope.current_user = '';
};
});
app.config(function($routeProvider){
$routeProvider
//the timeline display
.when('/', {
templateUrl: 'main.html',
controller: 'mainController'
})
//the login display
.when('/login', {
templateUrl: 'login.html',
controller: 'authController'
})
//the signup display
.when('/register', {
templateUrl: 'register.html',
controller: 'authController'
})
//search
.when('/search', {
templateUrl: 'search.html',
controller: 'searchController'
});
});
app.factory('postService', function($resource){
return $resource('/api/posts/:id');
});
app.controller('mainController', function(postService, $scope, $rootScope){
$scope.posts = postService.query();
$scope.newPost = {created_by: '', text: '', created_at: ''};
$scope.post = function() {
$scope.newPost.created_by = $rootScope.current_user;
$scope.newPost.created_at = Date.now();
postService.save($scope.newPost, function(){
$scope.posts = postService.query();
$scope.newPost = {created_by: '', text: '', created_at: ''};
});
};
});
app.controller('searchController', function(postService, $scope, $rootScope){
$scope.posts = [];
$scope.posts = postService.get(text:"1223");
$scope.tiks=[];
$scope.newPost = {created_by: '', text: '', created_at: ''};
$scope.post = function() {
$scope.newPost.created_by = $rootScope.current_user;
$scope.newPost.created_at = Date.now();
postService.save($scope.newPost, function(){
$scope.posts = postService.query();
$scope.newPost = {created_by: '', text: '', created_at: ''};
});
};
});
app.controller('authController', function($scope, $http, $rootScope, $location){
$scope.user = {username: '', password: ''};
$scope.error_message = '';
$scope.login = function(){
$http.post('/auth/login', $scope.user).success(function(data){
if(data.state == 'success'){
$rootScope.authenticated = true;
$rootScope.current_user = data.user.username;
$location.path('/');
}
else{
$scope.error_message = data.message;
}
});
};
$scope.register = function(){
$http.post('/auth/signup', $scope.user).success(function(data){
if(data.state == 'success'){
$rootScope.authenticated = true;
$rootScope.current_user = data.user.username;
$location.path('/');
}
else{
$scope.error_message = data.message;
}
});
};
});
in the searchController am trying to query a specific post with text 123.
Here is my schema :
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var postSchema = new mongoose.Schema({
username: { type: Schema.ObjectId, ref: 'User' },
created_at: {type: Date, default: Date.now},
text: String
});
var userSchema = new mongoose.Schema({
username: String,
password: String, //hash created from password
created_at: {type: Date, default: Date.now}
})
mongoose.model('Post', postSchema);
mongoose.model('User', userSchema);

Related

Why list become empty outside the method in Angular js

I am using angular js and I have a get method '$scope.getAllEmployeesList'. In this method I put the response data into the '$scope.employeeList'. However, list contains data only inside the method but it become empty outside the get method.
Here is my code:
var app = angular.module('app', []);
app.controller('basicInfoController', function ($scope, $http, $location) {
$scope.submitForm = function () {
var url = "http://localhost:8080/basicInfo/save";
var data = {
employeeId: $scope.employeeId,
firstName: $scope.firstName,
lastName: $scope.lastName,
companyId: $scope.companyId,
phoneNo: $scope.phoneNo,
sexId: $scope.sexId,
sexName: $scope.sexName,
birthDate: $scope.birthDate,
joiningDate: $scope.joiningDate,
department: $scope.department
};
$http.post(url, data).then(function (response) {
$scope.postResultMessage = "Sucessful!";
$scope.successMessage = 'User created successfully';
}, function (response) {
$scope.postResultMessage = "Fail!";
});
$scope.employeeId = "";
$scope.firstName = "";
$scope.lastName = "";
$scope.companyId = "";
$scope.phoneNo = "";
$scope.sexId = "";
$scope.sexName = "";
$scope.birthDate = "";
$scope.joiningDate = "";
$scope.department = "";
}
$scope.employeeList =[];
$scope.getAllEmployeesList = function () {
var url = $location.absUrl() + "basicInfo/getAllEmployeeBasicInfo";
var config = {
headers: {
'Content-Type': 'application/json;charset=utf-8;'
}
}
$http.get(url, config).then(function (response) {
$scope.employeeList = response.data;
$scope.employeeList = angular.copy(response.data);
console.log($scope.employeeList);
}, function (response) {
$scope.getResultMessage = "Fail!";
});
}
$scope.getAllEmployeesList();
console.log($scope.employeeList);
function reset() {
$scope.basicInfo = {
employeeId: '',
firstName: '',
lastName: '',
phoneNo: '',
sex: '',
birthDate: '',
companyId: '',
department: '',
joiningDate: ''
};
$scope.myForm.$setPristine(); //reset Form
}
});
in $scope.getAllEmployeesList method, when I print 'console.log($scope.employeeList);' inside the method then it is showing value but if print out side the method then empty list is shown.
Just return the $http... then tack on another .then().
var app = angular.module('app', [])
.controller('basicInfoController', function ($scope, $http, $location) {
function submitForm() {
var url = "http://localhost:8080/basicInfo/save";
var data = {
employeeId: $scope.employeeId,
firstName: $scope.firstName,
lastName: $scope.lastName,
companyId: $scope.companyId,
phoneNo: $scope.phoneNo,
sexId: $scope.sexId,
sexName: $scope.sexName,
birthDate: $scope.birthDate,
joiningDate: $scope.joiningDate,
department: $scope.department
};
$http.post(url, data).then(function() {
$scope.postResultMessage = "Sucessful!";
$scope.successMessage = 'User created successfully';
}, function() {
$scope.postResultMessage = "Fail!";
});
$scope.employeeId = "";
$scope.firstName = "";
$scope.lastName = "";
$scope.companyId = "";
$scope.phoneNo = "";
$scope.sexId = "";
$scope.sexName = "";
$scope.birthDate = "";
$scope.joiningDate = "";
$scope.department = "";
}
$scope.employeeList = [];
function getAllEmployeesList() {
var url = $location.absUrl() + "basicInfo/getAllEmployeeBasicInfo";
var config = {
headers: {
'Content-Type': 'application/json;charset=utf-8;'
}
}
return $http.get(url, config).then(function() {
$scope.employeeList = response.data;
$scope.employeeList = angular.copy(response.data);
}, function() {
$scope.getResultMessage = "Fail!";
});
}
getAllEmployeesList().then(function() {
console.log($scope.employeeList);
});
function reset() {
$scope.basicInfo = {
employeeId: '',
firstName: '',
lastName: '',
phoneNo: '',
sex: '',
birthDate: '',
companyId: '',
department: '',
joiningDate: ''
};
$scope.myForm.$setPristine(); //reset Form
}
$scope.getAllEmployeesList = getAllEmployeesList;
$scope.submitForm = submitForm;
});

TypeError: $http.post(...).success is not a function [duplicate]

This question already has answers here:
AngularJS error .success is not a function
(6 answers)
Why are AngularJS $http success/error methods deprecated? Removed from v1.6?
(2 answers)
Closed 5 years ago.
After clicking on register button the site is showing success is not a function error.
its not getting registered because of it
please help!
This is the error
angular.js:14525 TypeError: $http.post(...).success is not a function
at b.$scope.register (chirpapp.js:63)
at fn (eval at compile (angular.js:15358), <anonymous>:4:144)
at e (angular.js:26994)
at b.$eval (angular.js:18161)
at b.$apply (angular.js:18261)
at HTMLFormElement.<anonymous> (angular.js:26999)
at HTMLFormElement.dispatch (jquery.min.js:3)
at HTMLFormElement.q.handle (jquery.min.js:3)
(anonymous) # angular.js:14525
(anonymous) # angular.js:11008
$apply # angular.js:18266
(anonymous) # angular.js:26999
dispatch # jquery.min.js:3
q.handle # jquery.min.js:3
This is my app.js
var app = angular.module('chirpApp', ['ngRoute']).run(function($rootScope){
$rootScope.authenticated = false;
$rootScope.current_user = '';
});
app.config(function($routeProvider){
$routeProvider
//the timeline display
.when('/', {
templateUrl: 'main.html',
controller: 'mainController'
})
//the login display
.when('/login', {
templateUrl: 'login.html',
controller: 'authController'
})
//the signup display
.when('/register', {
templateUrl: 'register.html',
controller: 'authController'
});
});
app.controller('mainController', function ($scope) {
$scope.posts = [];
$scope.newPost = {
created_by: '',
text: '',
created_at: ''
};
$scope.post = function () {
$scope.newPost.created_at = Date.now();
$scope.posts.push($scope.newPost);
$scope.newPost = {
created_by: '',
text: '',
created_at: ''
};
};
});
app.controller('authController', function($scope, $http, $rootScope, $location){
$scope.user = {username: '', password: ''};
$scope.error_message = '';
$scope.login = function(){
$http.post('/auth/login', $scope.user).success(function(data){
if(data.state == 'success'){
$rootScope.authenticated = true;
$rootScope.current_user = data.user.username;
$location.path('/');
}
else{
$scope.error_message = data.message;
}
});
};
$scope.register = function(){
$http.post('/auth/signup', $scope.user).success(function(data){
if(data.state == 'success'){
$rootScope.authenticated = true;
$rootScope.current_user = data.user.username;
$location.path('/');
}
else{
$scope.error_message = data.message;
}
});
};
});
After clicking on register button the site is showing success is not a function error.
its not getting registered because of it
please help!
ckech "authcontroller" the error is in register so it might be in $scope.register=function(...)

Unknown provider: postPromiseProvider <- postPromise <- MainCtrl

I have my angularApp written
var app = angular.module('flapperNews', ['ui.router']);
app.factory('posts', ['$http',function($http) {
var posts = [
{ title: 'post 1', upvotes: 5 },
{ title: 'post 2', upvotes: 2 },
{ title: 'post 3', upvotes: 15 },
{ title: 'post 4', upvotes: 9 },
{ title: 'post 5', upvotes: 4 }
];
var service = {};
service.getAll = function() {
return $http.get('/posts').success(function(data){
angular.copy(data, posts);
});
};
service.create = function(post) {
return $http.post('/posts', post).success(function(data){
posts.push(data);
});
};
service.getPosts = function() {
return posts;
};
service.upvote = function(post) {
return $http.put('/posts/' + post._id + '/upvote').success(function(data){
post.upvotes += 1;
});
};
service.get = function(id) {
return $http.get('/posts/'+id).then(function(res) {
return res.data;
});
}
return service;
}]);
app.controller('MainCtrl', ['$scope', 'postPromise',
function($scope, postPromise) {
$scope.posts = postPromise;
$scope.title = null;
$scope.link = null;
$scope.test = "Hello World";
$scope.addPost = function() {
if (!$scope.title || $scope.title === '') {
return;
} else {
posts.create({
title: $scope.title,
link: $scope.link,
});
$scope.link = '';
$scope.title = '';
}
};
$scope.incrementUpvotes = function(post) {
posts.upvote(post);
};
}
]);
app.controller('PostsCtrl', [
'$scope',
'posts',
'post',
function($scope, posts, post) {
$scope.post = post;
$scope.addComment = function(){
if($scope.body === '') { return; }
$scope.post.comments.push({
body: $scope.body,
author: 'user',
upvotes: 0
});
$scope.body = '';
};
}
]);
app.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: '/home.html',
controller: 'MainCtrl',
resolve: {
postPromise: ['posts', function(posts){
return posts.getAll();
}]
}
})
.state('posts', {
url: '/posts/{id}',
templateUrl: '/posts.html',
controller: 'PostsCtrl',
resolve: {
post: ['$stateParams', 'posts', function($stateParams, posts) {
return posts.get($stateParams.id);
}]
}
});
$urlRouterProvider.otherwise('home');
}
]);
When I load the Homepage I get an error saying
Unknown provider: postPromiseProvider <- postPromise <- MainCtrl
I do not understand this.
I have tried restructuring the code, placing the factory above the Controllers, but it still throws the same error.
PS - The network call to retrieve posts is made (I can see it in the Browser Netwrok calls)
The name of your factory is posts not postPromise.
Change your MainCtrl to:
app.controller('MainCtrl', ['$scope', 'posts', function($scope, posts) {
});

Saving upvote value to database (MEAN stack - reddit clone)

I have been working on a reddit clone from the thinkster.io tutorial, and I can not figure out how to save upvote values to the database. Could some one please take a look?
// from angularApp.js
.factory('posts', ['$http', 'auth', function($http, auth){
var o = {
posts: []
};
o.upvote = function(post) {
return $http.put('/posts/' + post._id + '/upvote', {
headers: {Authorization: 'Bearer '+auth.getToken()}
}).success(function(data){
post.votes += 1;
});
};
return o;
}])
.controller('MainCtrl', [
'$scope',
'posts',
'auth',
function($scope, posts, auth){
$scope.posts = posts.posts;
$scope.isLoggedIn = auth.isLoggedIn;
$scope.addPost = function(){
//prevents empty posts
if(($scope.title === '') || ($scope.body === '')) { return; }
//creates post
posts.create({
title: $scope.title,
votes: 0,
createdOn: Date.now(),
link: $scope.link,
body: $scope.body,
});
//returns empty values after post is created
$scope.title = '';
$scope.link = '';
$scope.body = '';
};
$scope.incrementUpvotes = function(post){
posts.upvote(post);
};
}])
//mongoose post schema
var PostSchema = new mongoose.Schema({
title: { type: String, required: '{PATH} is required!'},
body: String,
createdOn: { type: Date, default: Date.now },
votes: {type: Number, default: 0},
comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }],
author: String
});
PostSchema.methods.upvote = function(cb) {
this.votes += 1;
this.save(cb);
};
mongoose.model('Post', PostSchema);
// from index.js
// upvote a post
router.put('/posts/:post/upvote', auth, function(req, res, next) {
req.post.upvote(function(err, comment){
if (err) { return next(err); }
res.json(comment);
});
});
//from index.ejs (html)
<i ng-click="incrementUpvotes(post)" class="ion-chevron-up"></i><br>
{{comment.votes}}<br>
o.upvote = function(post) {
return $http.put('/posts/' + post._id + '/upvote', null, { ...

how to load more than one service in $state resolve?

I want to load two APIs before page is going to load For it i have used the following code in $stateProvider
.state('admin-panel.default.jobadd', {
url: '/jobadd/:jobID',
templateUrl: 'app/search/jobadd.tmpl.html',
controller: 'JobaddController',
resolve: {
jobAdd: ['Search', '$stateParams','$q', function(Search,$stateParams,$q) { //Search is service
var jobAdd = Search.jobAdd($stateParams.jobID);
var isApplied = Search.is_job_applied($stateParams.jobID);
jobAdd.$promise.then(function(response) {console.log('Resource 1 data loaded!')});
isApplied.$promise.then(function(response) {console.log('Resource 2 data loaded!')});
return $q.all([jobAdd.$promise, isApplied.$promise]);
}]
},
data: {
requireLogin: true
}
});
})
But it's not give the data when injects to the controller, page seems as blank
my controller code is
.controller('JobaddController', function ($scope, $mdDialog, $state, jobAdd, Profile) {
$scope.jobs = jobAdd[0];
$scope.benifits = jobAdd[0].benifits;
if($scope.jobs.short_listed == 1)
$scope.jobs.flag = true;
else
$scope.jobs.flag = false;
$scope.checkShortList= function(job){
if(job.flag){
Profile.rmShortList(job.short_list_id);
job.flag = false;
}
else{
if(job.short_list_id === null){
Profile.addNewShortList(job.id).then(function(response){
job.short_list_id = response.short_list_id;
});
}
else
Profile.addShortList(job.short_list_id,job.id);
job.flag = true;
}
};
$scope.companyModal = function(ev) {
$mdDialog.show({
controller: 'CompanyDetailsController',
templateUrl: 'app/search/company-details.tmpl.html',
parent: angular.element(document.body),
targetEvent: ev,
})
.then(function(answer) {
$scope.alert = 'You said the information was "' + answer + '".';
}, function() {
$scope.alert = 'You cancelled the dialog.';
});
};
$scope.applyModal = function(ev) {
$mdDialog.show({
controller: 'ApplyController',
templateUrl: 'app/search/apply.tmpl.html',
locals: { Jobid: $scope.jobs.id },
parent: angular.element(document.body),
targetEvent: ev,
resolve: {
shortProfile: ['Profile', function(Profile) {
return Profile.shortProfile();
}]
},
})
.then(function(answer) {
$scope.alert = 'You said the information was "' + answer + '".';
}, function() {
$scope.alert = 'You cancelled the dialog.';
});
};
var container = angular.element(document.getElementById('container'));
var section2 = angular.element(document.getElementById('section-2'));
$scope.toTheTop = function() {
container.scrollTop(0, 5000);
};
$scope.toSection2 = function() {
container.scrollTo(section2, 0, 1000);
};
})
in service code
.service('Search', [ '$http', '$q', 'API',
function($http, $q, API) {
var data = '';
this.jobAdd = function(job_id) {
var def = $q.defer();
$http({
url: API.url+'get_job_add_detail?job_id=' + job_id,
method: "GET"
}).success(function(response) {
if(response.status == 'Success'){
data = response.data;
def.resolve(data);
}
}).error(function(response) {
console.log (response);
if(response.status == 'Failed'){
data = response.msg;
def.reject(data);
}
});
return def.promise;
}
this.isJobApplied = function(job_id) {
var def = $q.defer();
$http({
url: API.url+'is_job_applied?job_id='+job_id,
method: "GET",
}).success(function(response) {
if(response.status == 'Success'){
data = response.data;
def.resolve(data);
}
}).error(function(response) {
console.log (response);
if(response.status == 'Failed'){
data = response.msg;
def.reject(data);
}
});
return def.promise;
}
}]);
What's the wrong here?? how to attach more than on service in $state resolve?
simply you can for more than one service.
resolve: {
jobAdd: ['Search', '$stateParams', function(Search,$stateParams) {
return Search.jobAdd($stateParams.jobID);
}],
isApplied: ['Search', '$stateParams', function(Search,$stateParams) {
return Search.isJobApplied($stateParams.jobID);
}]
}

Resources