Using $resource to delete from database - angularjs

I'm having trouble getting my head around $resource. I'm trying to apply a delete method to remove a MongoDB database entry when user presses a delete button. I am using Angular 1.4 with Express and Mongoose.
Here is my HTML:
<body ng-app="polls" ng-controller="PollsCtrl">
Polls:
<ul>
<li ng-repeat="question in questions">
{{ question.questionName }}
<button ng-click="deletePoll(question._id, $index)">Delete</button>
</li>
</ul>
...
Here's the client-side controller:
"use strict";
var app = angular.module('polls', ['ngResource']);
app.controller('PollsCtrl', function ($scope, $resource) {
var Poll = $resource('/api/polls');
var PollID = $resource('/api/polls/:pollID');
Poll.query(function (results) {
$scope.questions = results;
});
$scope.questions = [];
$scope.questionName = '';
$scope.addPoll = function () {
var poll = new Poll();
poll.questionName = $scope.questionName;
poll.$save(function (result) {
$scope.questions.push(result);
$scope.questionName = '';
});
};
$scope.deletePoll = function (id, index) {
var poll = new PollID();
poll.$remove(function () {
$scope.questions.splice(index, 1);
});
};
});
here's the server file including the remove method:
var express = require('express');
var path = require('path');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var app = express();
mongoose.connect('mongodb://localhost/poll-app');
app.use('/controllers', express.static(__dirname + '/controllers'));
app.use('/bower_components', express.static(__dirname + '/bower_components'));
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.get('/polls', function (req, res) {
res.sendFile(path.join(__dirname + '/polls.html'));
});
app.get('/add-poll', function (req, res) {
res.sendFile(path.join(__dirname + '/add-poll.html'));
});
var pollSchema = new mongoose.Schema({questionName: String});
var Poll = mongoose.model('Poll', pollSchema);
var creater = function (req, res) {
var poll = new Poll(req.body);
poll.save(function (err, result) {
if (err) throw err;
res.json(result);
})
};
var list = function (req, res) {
Poll.find({}, function (err, result) {
if (err) throw err;
res.json(result);
});
};
var remove = function (req, res) {
console.log(req.params);
var poll = new Poll(req.body);
poll.remove({_id: req.params}, function (err, result) {
if (err) throw err;
res.json(result);
});
};
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.post('/api/polls', creater);
app.get('/api/polls', list);
app.delete('/api/polls/:pollID', remove);
app.listen(3000, function () {
console.log('HI');
});
I'm pretty sure the error lies in the server's remove() method. When i test this, i actually get:
DELETE http://localhost:3000/api/polls 404 (Not Found)
as though it isn't routing to where i want it to.

poll.$remove({pollID:id}, function () {
$scope.questions.splice(index, 1);
})

in your case, I think it's better to use $http:
$http.delete('/api/polls/pollID/'+req.params).
This way, you don't have to get the object before delete

Related

Can't get Route angular

I can't open the route "/d" but "/" is working. What could be the problem? I tried different things but id did not find a solution.
var myApp = angular.module('myApp',['ngRoute']);
myApp.config(function ($routeProvider) {
$routeProvider.when('/', {
controller: 'OrdersController',
templateUrl: 'views/lp.html'
})
.when('/d',{
controller:'OrdersController',
templateUrl: 'views/order_detail.html'
})
.otherwise({
redirectTo: '/'
});
});
Server side code looks like this. Maybe they don't like each other ;)
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
app.use(express.static(__dirname+'/client'));
app.use(bodyParser.json());
Order = require('./models/order.js');
//Connect to Mongoose
mongoose.connect('mongodb://localhost/groundlevel');
var db = mongoose.connection;
app.get('/', function(req, res){
res.send('Please use /api/order');
});
app.get('/api/orders', function (req, res) {
Order.getOrders(function (err, orders) {
if(err){
throw err;
}
res.json(orders);
})
});
app.get('/api/orders/:_id',function (req, res) {
Order.getOrderById(req.params._id, function (err, order) {
if(err){
throw err;
}
res.json(order);
})
});
app.post('/api/orders', function (req, res) {
var order = req.body;
Order.addOrder(order, function (err, order) {
if(err){
throw err;
}
res.json(order);
})
});
app.listen(3000);
console.log('Running on Port 3000...');
To let your client side application handle the routing. In your server side do the following
var path= require('path');
// All other routes should redirect to the index.html
app.route('/*')
.get((req, res) => {
res.sendFile(path.resolve(__dirname + '/client/index.html'));
});

AngularJs Server Node js /get

Hello I have for this moment a fake backend with httpbackend in my angular Project. But I want to transfer my fake backend in a server node js but I don't know.
So For this moment I have this :
var express = require('express')
, path = require('path')
, fs = require('fs')
, bodyParser = require('body-parser')
, morgan = require('morgan');
var apps = express();
var staticRoot = __dirname + '/';
apps.set('port', (process.env.PORT || 3000));
apps.use(express.static(staticRoot));
apps.use(bodyParser.urlencoded({ extended: false }));
apps.use(bodyParser.json());
apps.use(morgan('dev'));
apps.use(function (req, res, next) {
var ext = path.extname(req.path);
if (ext !== '') {
return next();
}
});
apps.get('/getTpl', function (req, res) {
res.writeHead(200);
res.end(JSON.parse(["tp1", "tp2", "tp3", "tp4", "tp5", "tp6", "tp7"]));
});
apps.listen(apps.get('port'), function () {
console.log('serveur en route, port : ', apps.get('port'));
});
My controller :
ctrl.tpls = [];
ctrl.tplJson = undefined;
diapoService.getTpl().then(function (response) {
ctrl.tpls = JSON.stringify(response.data);
console.log(response.data);
});
function getTpl() {
return $http({
method: 'GET'
, url: '/getTpl'
});
I want to send my array in my select but my select is empty why ? please
Thank you so much for your answer
You have to change this function:
apps.get('/getTpl', function (req, res) {
res.status(200).json(["tp1", "tp2", "tp3", "tp4", "tp5", "tp6", "tp7"]);
});
Additionally I do not use Angular, but I don't think that you have to stringify the response:
diapoService.getTpl().then(function (response) {
ctrl.tpls = JSON.stringify(response.data); // <- Is this necessary?
console.log(response.data);
});

How to add a new object with AngularJS and mongoDB

I'm using NodeJS, ANgularJS, and MongoDB with mongoose to make a website. I'm having some trouble adding an object in mongoDB. The name of the object is Todo.
Here are the models of Todo:
var mongoose = require('mongoose');
var TodoSchema = new mongoose.Schema({
name: String,
password : String,
completed: Boolean,
note: String
});
module.exports = mongoose.model('Todo', TodoSchema);
In the controller I create a new Todo and push it
angular.module('app').controller('Connexion', ['$scope', 'Todos','$location', function($scope,Todos, $location) {
$scope.editing = [];
$scope.todos = Todos.query();
$scope.save = function() {
var todo = new Todos({ name: "test", password: "test", completed: false });
$scope.todos.push(todo);
Todos.save($scope.todo);
}
}]);
This is my html page, each time I click on the button I Have a new todo created and it's displayed on screen:
<button ng-click="save()">Creer POST </button>
<ul>
<li ng-repeat="todo in todos">
{{todo.name}}
{{todo.password}}
</li>
</ul>
But I have a problem, the new object is not added on the database. How can I do it?
This is my files in the back-end :
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Todo = require('../models/Todo.js');
/* GET /todos listing. */
router.get('/', function(req, res, next) {
Todo.find(function (err, todos) {
if (err) return next(err);
res.json(todos);
});
});
/* POST /todos */
router.post('/', function(req, res, next) {
Todo.create(req.body, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* GET /todos/id */
router.get('/:id', function(req, res, next) {
Todo.findById(req.params.id, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* PUT /todos/:id */
router.put('/:id', function(req, res, next) {
Todo.findByIdAndUpdate(req.params.id, req.body, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* DELETE /todos/:id */
router.delete('/:id', function(req, res, next) {
Todo.findByIdAndRemove(req.params.id, req.body, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
module.exports = router;
And if this can help this the back-end file app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongo = require('mongodb');
var Post = require('./models/Post.js');
var routes = require('./routes/index');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/todoApp', function(err) {
if(err) {
console.log('connection error', err);
} else {
console.log('connection successful');
}
});
var app = express();
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', function(req, res, next){
res.sendFile(__dirname + '/public/index.html');
});
var found = ['DB Connection not yet established. Try again later. Check the console output for error messages if this persists.'];
module.exports = app;
$scope.todo from Todos.save($scope.todo); is not defined so this is why you might not manage to save anything

Trouble with MongoDB insert

Currently using MEAN in order to connect my AngularJS app to a database.
I have a button called "commit to database" that first clears the mongodb database, then inserts my array of data (stored in $scope.filterTable) into the database.
I then have a button called "load from database" that updates $scope.filtertable to match data from the database.
Half of the time when I click the "commit to database" button, my database is empty. Half of the time, it's filled with the data I expect it to have.
Anyone know what I'm doing wrong? Thanks!
Here's the code in my main AngularApp:
var commitToDatabase = function(){
deleteDatabase();
insertDatabase();
}
var insertDatabase = function(){
$http.post("/AngularApp", $scope.filterTable).success(function(response){
$http.get('/AngularApp').success(function(response) {
console.log(response);
});
});
}
var deleteDatabase = function(){
$http.delete('/AngularApp');
}
var loadFromDatabase = function(){
$http.get('/AngularApp').success(function(response) {
$scope.filterTable = response;
});
}
Here's the code in my server.js file:
var express = require("express");
var mongojs = require("mongojs");
var bodyParser = require("body-parser");
var app = express();
var db = mongojs("AngularApp", ["AngularApp"]);
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());
app.get('/AngularApp', function (req, res) {
console.log('I received a GET request');
db.AngularApp.find(function (err, docs) {
console.log(docs);
res.json(docs);
});
});
app.post('/AngularApp', function (req, res) {
console.log("POST");
console.log(req.body);
db.AngularApp.insert(req.body, function(err, doc) {
res.json(doc);
});
});
app.delete('/AngularApp', function(req, res){
db.AngularApp.remove({},function(err, doc){
res.json(doc);
});
});
app.listen(3000);
console.log("Server running on point 30000");

AngularJS - Socket.io - ExpressJS : How to set up a realtime counter?

My purpose is to create a realtime counter. Actually I'm creating files with my server. And I want for every created file, the counter to be incremented (the client should see the number of files in the browser growing...)
How can I exactly do that using Socket.io, AngularJS and Express.js ?
P.S : I have already written some code, but vainly.
EDIT 1 :
public/core.js
var app = angular.module('app', []);
app.factory('socket', function($rootScope){
var socket = io.connect();
return{
on: function(eventName, callback){
socket.on(eventName, function(){
var args = arguments;
$rootScope.$apply(function(){
callback.apply(socket, args);
});
});
},
emit: function(eventName, data, callback){
socket.emit(eventName, data, function(){
var args = arguments;
$rootScope.$apply(function(){
if(callback){
callback.apply(socket.args);
}
});
})
}
};
});
function mainController($scope, $http, socket) {
$scope.formData = {};
socket.on('number', function (data) {
console.log("Socket on number core.js !");
$scope.number = data.numberOfFiles;
});
$scope.initialize = function() {
$scope.formData.search = "";
console.log("initialize() body !");
};
$scope.search = function() {
socket.emit('next', {
message: "next"
});
console.log("search() body !");
$http.post('/search', $scope.formData)
.success(function() {
$('input').val('');
})
.error(function(data) {
console.log('Error: ' + data);
});
};
}
app.js
/**
* Module dependencies.
*/
var express = require('express');
var request = require('request');
var http = require('http');
var path = require('path');
var url = require('url');
var cheerio = require('cheerio'); // builds the DOM tree
var fs = require('fs');
var app = express();
// all environments
app.configure(function() {
app.use(express.static(__dirname + '/public')); // set the static files location /public/img will be /img for users
app.use(express.logger('dev')); // log every request to the console
app.use(express.bodyParser()); // pull information from html in POST
app.use(express.methodOverride()); // simulate DELETE and PUT
app.use(express.json());
app.use(express.urlencoded());
app.use(app.router);
});
// app.listen(8080);
// console.log("App listening on port 8080");
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(8080);
var numberFiles = 1;
app.post('/search', function(req, res){
var keyword = req.body.search;
for(var i = 0; i < 100; i++) {
// The results' page URL
// some long logic that creates files and increments numberFiles
numberFiles++;
}
});
io.sockets.on('connection', function (socket) {
socket.on('next', function (data) {
socket.emit('number', {
numberOfFiles: numberFiles
});
});
});
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)
});
Have you tried:
SERVER
io.sockets.on('connection', function (socket) {
socket.on('next', function (data, respond) {
respond({
numberOfFiles: numberFiles
});
});
});
CLIENT
socket.emit('next', {
message: "next"
}, function(data){ // data.numberOfFiles ... };

Resources