This is my first Stackoverflow post, i'll try to make it simple. I have to build a social network with the mean stack for my school. Pretty amazingg technology but i can't find how to use properly the function population of mongoose for linking comments to posts. My comments are saved in the database but appared in all the posts on my first page. Can you tell me what i done wrong ? Thanks in advance !
Here's my view post
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<form ng-submit="pst.sendPost()">
<div class="form-group">
<label for="text">Your post</label>
<input type="text" class="form-control" id="text" placeholder="share your thoughts..." ng-model="pst.newpst.text">
</div>
<button type="submit" class="btn btn-default">Post</button>
</form><br>
<div ng-repeat="post in pst.posts | orderBy: '-'">
<div class="well">{{post.text}}
<br><form ng-submit="pst.sendComment(post._id)">
<br><div class="well">
<label for="comment"></label>
<input type="text" class="form-control" id="comment" placeholder="comment..." ng-model="pst.newcmt.text">
</div>
<div ng-repeat="comment in pst.comments| orderBy: '+'" class="alert alert-info" role="alert">{{comment.text}}<br>{{comment._id}}
<button class="btn btn-primary" type="button" ng-click="pst.removeComment(comment._id)"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span></button>
</div>
</form>
<button class="btn btn-primary" type="button" ng-click="pst.removePost(post._id)">Remove Post</button>
</div>
</div>
</body>
</html>
Here's my angular controller
angular.module('app')
.controller('PostController', function($scope, $http) {
var _this = this;
this.getPosts = function() {
$http.get('/api/posts')
.then(function(res){
_this.posts = res.data;
});
};
this.getPosts();
this.removePost = function(id) {
$http.delete('/api/posts/' + id)
.then(function(){
_this.getPosts();
});
};
this.sendPost = function() {
if (!this.newpst || !this.newpst.text)
return;
$http.post('api/posts', this.newpst)
.then(function(){
_this.getPosts();
});
this.newpst = {};
};
this.updatePost = function(id) {
$http.post('/api/posts/' + id)
.then(function(){
_this.getPosts();
});
};
this.getComments = function() {
$http.get('/api/comments')
.then(function(res){
_this.comments = res.data;
});
};
this.getComments();
this.removeComment = function(id) {
console.log(id);
$http.delete('/api/comments/' + id)
.then(function(){
_this.getComments();
});
};
this.sendComment = function(id) {
this.newcmt.post = id
console.log(this.newcmt)
$http.post('api/comments', this.newcmt)
.then(function(){
_this.getComments();
});
this.newcmt = {};
};
this.updateComment = function(id) {
$http.post('/api/comments/' + id)
.then(function(){
_this.getComments();
});
};
})
Here's my post.model.js
var mongoose = require('mongoose');
module.exports = mongoose.model('Post', {
text: {
type: String,
default: ''
},
image: {
type: String,
default: ''
},
comment1: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Comment'
}]
});
my routes_posts.js
var Post = require('./post.model');
module.exports = function(app) {
app.delete('/api/posts/:id', function(req, res) {
Post.remove({_id: req.params.id}, function(err) {
(err ? res.send(err) : res.status(200).send());
});
});
app.get('/api/posts', function(req, res) {
Post.find({})
.populate('comment')
.exec(function(err, posts){
(err ? console.log(err) : res.json(posts))
})
});
app.post('/api/posts', function(req, res) {
Post.create(req.body, function(err) {
(err ? res.send(err) : res.status(200).send());
});
});
};
my comment.model.js
var mongoose = require('mongoose');
module.exports = mongoose.model('Comment', {
text: {
type: String,
default: ''
},
post: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Post',
}
});
my routes_comment.js
var Comment = require('./comment.model');
var Post = require('../posts/post.model')
module.exports = function(app) {
app.get('/api/comments', function(req, res) {
Post.find({})
.populate('post_id')
.exec(function(err, comments){
(err ? console.log(err) : res.json(comments))
})
});
app.post('/api/comments', function(req, res) {
console.log(req)
Comment.create(req.body, function( err) {
(err ? res.send(err) : res.status(200).send());
});
});
app.delete('/api/comments/:id', function(req, res) {
Comment.remove({_id: req.params.id}, function(err) {
(err ? res.send(err) : res.status(200).send());
});
});
};
Thanks !
Related
my index.js file and views/products/edit.ejs files :
const express = require('express')
const path = require('path')
const mongoose = require('mongoose');
const methodOverride = require('method-override')
const app = express()
app.set('view engine', 'ejs')
app.set('views', path.join(__dirname, "views"))
app.use(express.urlencoded({
extended: true
}))
app.use(methodOverride('_method'))
mongoose.connect('mongodb://localhost:27017/farmStand')
.then((data) => {
console.log("successfully connected to database")
console.log(data)
}).catch(error => {
console.log("error occured")
console.log(error)
})
function wrapperASync(fn) {
return function(req, resp, next) {
fn(req, resp, next).catch((e) => {
next(e)
})
}
}
let categories = ['fruits', 'vegetables', 'dairy']
const Product = require('./models/product');
const {
param
} = require('express/lib/request');
app.get('/', (req, resp) => {
resp.send("getting data")
})
app.get('/products', async(req, resp) => {
const {
category
} = req.query
const selectedcategory = category
console.log(selectedcategory)
if (selectedcategory) {
let products = await Product.find({
category: selectedcategory
})
resp.render("products/index", {
products,
selectedcategory
})
} else {
let products = await Product.find({})
// console.log("found products")
resp.render("products/index", {
products,
selectedcategory: "All"
})
}
})
app.get('/products/:id', async(req, resp, next) => {
const {
id
} = req.params
let myproduct = await Product.findById(id)
if (!myproduct) {
return next(new AppError("product not found", 404))
}
// console.log(myproduct)
resp.render('products/details', {
myproduct
})
})
app.get('/product/new', (req, resp) => {
resp.render('products/new', {
categories
})
})
app.get('/products/:id/edit', wrapperASync(async(req, resp, next) => {
const {
id
} = req.params
const product = await Product.findById(id)
if (!product) {
throw new AppError("product not found", 404)
}
resp.render('products/edit', {
product,
categories
})
}))
app.put('/products/:id', wrapperASync(async(req, resp, next) => {
const {
id
} = req.params
const updatedValues = req.body
const newvalue = await Product.findByIdAndUpdate(id, updatedValues, {
runValidators: true,
new: true
})
// console.log(newvalue)
resp.redirect(`/products/${newvalue._id}`)
}))
app.post('/products', wrapperASync(async(req, resp) => {
const newdoc = req.body
const myproduct = new Product(newdoc)
console.log(myproduct)
await myproduct.save()
resp.redirect(`/products/${myproduct._id}`)
}))
app.delete('/products/:id', async(req, resp, next) => {
try {
const {
id
} = req.params
const deleted_product = await Product.findOneAndDelete(id)
resp.redirect('/products')
} catch (error) {
next(error)
}
})
app.use((err, req, resp, next) => {
console.log(err.name)
next(err)
})
app.use((err, req, resp, next) => {
const {
status = 404, message = "something went wrong"
} = err
resp.status(status).send(message)
})
app.listen(3000, () => {
console.log("server started successfully")
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1> enter product details</h1>
<form action="/products/<%= product.id %>?_method=PUT " method="POST">
<label for="name">enter the name of the product : </label>
<input type="text" name="name" id="name" placeholder="name" value="<%= product.name %> ">
<label for="price">enter the price in dollars : </label>
<input type="number" name="price" id="price" placeholder="price" value="<%= product.price %>">
<label for="category">category : </label>
<select name="category" id="category">
<% for(category of categories) { %>
<option value="<%= category %>" <%=p roduct.category===c ategory ? "selected": '' %> >
<%= category %>
</option>
<% } %>
</select>
<button>add new details</button>
</form>
<section>
exit
</section>
</body>
</html>
my models/product.js file :
const mongoose = require('mongoose')
const productSchema = new mongoose.Schema({
name : {
type : String,
required : true
},
price:{
type : Number,
required : true,
min : 0
},
category:{
type:String,
lowercase :true,
enum : ["fruits","vegetables","dairy"]
}
})
const Product = new mongoose.model('Product',productSchema);
module.exports = Product;
my problem : I have installed all the dependencies my problem is when I am entering in to the edit page and then when I type my id incorrect and of different length in the url for which Iam listening for I get the CastError printed out on my console and when I keep my name Field as blank and edit then I get the ValidationError printed out on my console but after getting the validation error when I change the id of the product which is incorrect again and which is of different length in the url after getting validation error response and send the request in chrome my server gets error and breaks even though I handle the error of my /products/:id put route
please help me
i'm building a web page for a library with node and mongoose in atom. I've created a log in form, register and an "add book". Now in the home page i want to see all the books and i dont know to to do that. I know it way have something to do with double {{}} or triple {{{}}} brackets but I'm not sure. I will put it later in a prettyer form, for now i just want to see how I can print, for example the titles. Btw i'm using the handlebars view engine.
<h2 class="page-header">Cartile existente</h2>
<h4>In curand!</h4> // <- there I'm supposed to put the book titles.
<h2 class="page-header">Adauga o carte noua</h2>//this is the "add a book"
{{#if errors}}
{{#each errors}}
<div class="alert alert-danger">{{msg}}</div>
{{/each}}
{{/if}}
<form method="post" action="/booksImp/addbook">
<div class="form-group">
<label>Numar Inventar</label>
<input type="text" class="form-control" placeholder="Numar curent" name="nrinv">
</div>
<div class="form-group">
<label>Titlu</label>
<input type="text" class="form-control" placeholder="Titlu" name="titlu">
</div>
<div class="form-group">
<label>Autor</label>
<input type="text" class="form-control" placeholder="Autor" name="autor">
</div>
<div class="form-group">
<label>Editura</label>
<input type="text" class="form-control" placeholder="Editura, Locul publicatiei" name="editura">
</div>
<div class="form-group">
<label>An</label>
<input type="text" class="form-control" placeholder="An publicatie" name="an">
</div>
<div class="form-group">
<label>Pret</label>
<input type="text" class="form-control" placeholder="Pret" name="pret">
</div>
<button type="submit" class="btn btn-success">Trimite</button>
</form>
var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');
var BookSchema = mongoose.Schema({
nrinv: {
type: String,
index: true
},
titlu: {
type: String
},
autor: {
type: String
},
editura: {
type: String
},
an: {
type: String
},
pret: {
type: String
}
});
var Book = module.exports = mongoose.model('bookImp', BookSchema);
module.exports.getBooks = (callback, limit) => {
Book.find(callback).limit(limit);
}
module.exports.getBookById = (id, callback) => {
Book.findById(id, callback);
}
module.exports.addBook = (book, callback) => {
Book.create(book, callback);
}
module.exports.removeBook = (id, callback) => {
var query = {
_id: id
};
BookImp.remove(query, callback);
}
var express = require('express'); //this is the controller code =))))
var router = express.Router();
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var Book = require('../models/bookImp');
router.get('/addbook', ensureAuthenticated, function(req, res, next) {
res.render('addbook');
});
router.post('/addbook', function(req, res, next) {
var nrinv = req.body.nrinv;
var titlu = req.body.titlu;
var autor = req.body.autor;
var editura = req.body.editura;
var an = req.body.an;
var pret = req.body.pret;
//console.log(name);
req.checkBody('nrinv', 'Introduceti numarul de inventar').notEmpty();
req.checkBody('titlu', 'Introduceti titlul').notEmpty();
req.checkBody('autor', 'Introduceti autorul').notEmpty();
req.checkBody('editura', 'Introduceti editura si locul').notEmpty();
req.checkBody('an', 'Introduceti anul').notEmpty();
// req.checkBody('an', 'Introduceti anul').isnumber();
req.checkBody('pret', 'Introduceti pretul').notEmpty();
var errors = req.validationErrors();
if (errors) {
res.render('addbook', {
errors: errors
});
} else {
var newBook = new Book({
nrinv: nrinv,
titlu: titlu,
autor: autor,
editura: editura,
an: an,
pret: pret
});
Book.addBook(newBook, function(err, book) {
if (err) throw err;
console.log(book);
});
req.flash('success_msg', 'Ati adaugat o carte cu succes');
res.redirect('/booksImp/addbook');
}
});
router.post('/addbook',
passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/booksImp/addbook',
failureFlash: true
}),
function(req, res) {
res.redirect('/');
});
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return next();
} else {
//req.flash('error_msg', 'Trebuie sa va logati');
res.redirect('/users/login');
}
}
module.exports = router;
var express = require('express');
var router = express.Router();
var Book = require('../models/bookImp');
router.get('/', ensureAuthenticated, function(req, res, next) {
res.render('index');
});
router.get('/api/books', ensureAuthenticated, function(req, res) {
Book.getBooks(function(err, books) {
if (err) {
throw err;
}
res.json(books);
});
});
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return next();
} else {
//req.flash('error_msg', 'Trebuie sa va logati');
res.redirect('/users/login');
}
}
module.exports = router;
I'm trying to get a "success" or "failure" response from my server to client. The server is being implemented in node.js in express framework and the client in angularjs.
Here is the server side node.js part:
connection.connect();
/* GET home page. */
router.get('/', function(req, res, next) {
res.sendFile(path.join(__dirname, '../', 'views', 'login.html'));
});
router.get('/login', function(req,res)
{
console.log("Username:"+req.query.username);
console.log("Password:"+req.query.password);
var user = req.query.username;
var pass = req.query.password
connection.query("select * from user where login_name = ?", user, function(err, rows, fields) {
if (!err){
if(user==rows[0].login_name && pass==rows[0].pass){
console.log("success");
res.json({status: 200});
}
}
else
console.log('Error while performing Query.', err);
});
and here is the angularjs part:
<form name="login">
<div class="login" ng-app="loginPage" ng-controller="loginController">
<input type="text" placeholder="username" ng-model="uname" name="userid"><br>
<input type="password" placeholder="password" ng-model="pword" name="pswrd"><br>
<!--<input type="button" ng-click="login();" onclick="check(this.form)" value="Login"/>-->
<button ng-click="login();">Login</button>
</div>
</form>
<script language="javascript">
var app = angular.module('loginPage', []);
app.controller('loginController', function($scope, $http) {
console.log("inside controller");
$scope.login = function() {
console.log("inside the login function");
console.log($scope.uname);
var verify = $http({
method: 'GET',
url: '/login' +
'',
params: { username: $scope.uname, password: $scope.pword }
}).then(
function successful(response) {
$scope.theResponse = response.data;
window.open("./team_list.html")
}, function unsuccessful(response) {
alert('Wrong username/password.');
$scope.theResponse = response.data;
});
}
})
</script>
I try to type in "test" for username and "test" for pw on the login page on the browser because that is what I have entered in my sql database. Specifically I'm not sure why the login page doesn't link to the team_list page that I have specified the path for.
I'm not really sure why it's not working. If I'm supposed to be using json differently, I would appreciate more help because I am not very familiar with it.
The order of the routing in the NodeJS side is wrong. The /login should come first. Else everything will be served by the '/' route.
router.get('/login', function(req, res) {
console.log("Username:" + req.query.username);
console.log("Password:" + req.query.password);
var user = req.query.username;
var pass = req.query.password
connection.query("select * from user where login_name = ?", user, function(err, rows, fields) {
if (!err) {
if (user == rows[0].login_name && pass == rows[0].pass) {
console.log("success");
res.json({
status: 200
});
}
} else
console.log('Error while performing Query.', err);
});
/* GET home page. */
router.get('/', function(req, res, next) {
res.sendFile(path.join(__dirname, '../', 'views', 'login.html'));
});
Check your console you can even figure out the problem from there.
Shortcuts for console
shortcut keys for opening different browsers's Console
do it like this :
connection.query("select * from user where login_name = ?", user, function(err, rows, fields) {
if (!err){
if(user==rows[0].login_name && pass==rows[0].pass){
console.log("success");
res.send(200);
}
}
else{
console.log('Error while performing Query.', err);
res.send(401);
}
});
Actually, you should send Error or Success code like 200 or 401.
And use
res.send(ErrorCode) or res.sendStatus(ErrorCode) and it'll autmatically do it for you at client side like below :
<script language="javascript">
var app = angular.module('loginPage', []);
app.controller('loginController', function($scope, $http, $window) {
console.log("inside controller");
$scope.login = function() {
console.log("inside the login function");
console.log($scope.uname);
$http.get('/login').then(function (success) {
$window.alert('Success');
}, function (error) {
$window.alert('Wrong username/password.');
});
}
});
</script>
I am running into an issue where my POST route from a form submissions redirects correctly without any issues, but none of the information is passed on to a document in database. I am not sure the best way to debug this issue.
blogpost-create.ejs
<html>
<head>
<% include ../partials/head %>
<script src="//cdn.ckeditor.com/4.4.5/standard/ckeditor.js"></script>
</head>
<body>
<header>
<% include ../partials/header %>
</header>
<div class="grid grid-pad">
<div class="col-1-1">
<h1>Blog Create</h1>
<form action="/admin/posts/create" method="POST">
Title: <input type="text" name="title"><br>
Author:
<select name="author">
<option value="Author">Author</option>
</select><br>
Category:
<select name="category">
<option value="Analytics/SEO/SEM">Analytics/SEO/SEM</option>
<option value="Advice">Advice</option>
<option value="Programming">Programming</option>
<option value="Thoughts">Thoughts</option>
</select><br>
Tagline: <input type="text" maxlength="160" name="tagline"><br>
Content:<br>
<textarea name="content" id="blog-editor" rows="10" cols="80">
Text editor.
</textarea><br>
Tags: <input type="text" name="tags"><br>
<input type="submit" value="Submit">
</form>
</div>
</div>
<script>
// Replace the <textarea id="blog-editor"> with a CKEditor
// instance, using default configuration.
CKEDITOR.replace( 'blog-editor' );
</script>
<footer>
<% include ../partials/footer %>
</footer>
</body>
</html>
routes.js
var express = require('express');
var router = express.Router();
var blogDB = require('../config/blogDB.js');
var Blogpost = require('./models/blogModel.js');
var paginate = require('express-paginate');
//index
router.use(paginate.middleware(10, 50));
router.route('/')
// START GET method
.get(function(req, res, next) {
Blogpost.paginate({}, req.query.page, req.query.limit, function(err, pageCount, blogpost, itemCount) {
if (err) return next(err)
if (err)
res.send(err);
blogpost.title = req.body.title; // get the blog title
blogpost.author = req.body.author; // get the author name
blogpost.tagline = req.body.tagline; // get tagline
blogpost.content = req.body.content; // get the blog content
blogpost.category = req.body.category; // get the category
blogpost.tags = req.body.tags; // get the tags
res.format({
html: function() {
res.render('pages/index', {
blogpost: blogpost,
pageCount: pageCount,
itemCount: itemCount
})
},
json: function() {
res.json({
object: 'blogpost',
has_more: paginate.hasNextPages(req)(pageCount),
data: blogpost
})
}
}); // END res.format(html, json)
}); // END Blogpost.paginate
}); // END GET method
router.route('/admin/posts/create')
// START POST method
.post(function(req, res) {
var blogpost = new Blogpost(); // create a new instance of a Blogpost model
blogpost.title = req.body.title; // set the blog title
blogpost.author = req.body.author; // set the author name
blogpost.tagline = req.body.tagline; // set the tagline
blogpost.content = req.body.content; // set the blog content
blogpost.category = req.body.category; // set the category
blogpost.tags = req.body.tags; // set the tags
//Save Blog Post
blogpost.save(function(err) {
if (err)
res.send(err);
res.redirect(303, '/'); //NEEDS TO BE CHANGED
});
}) // END POST method
.get(function(req, res) {
res.render('pages/blogpost-create');
});
function getSearchCriteria(params) {
return {
title: params.blogpost_title
};
}
function getBlogpostUpdate(body) {
return {
title: body.title,
author: body.author,
tagline: body.tagline,
content: body.content,
category: body.category,
tags: body.tags
};
}
var blogpostsRoute = router.route('/blog/:blogpost_title');
// to manipulate your route params, use router.param
router.param('blogpost_title', function (req, res, next, blogpost_title) {
req.param.blogpost_title = blogpost_title.toLowerCase();
next();
});
blogpostsRoute
.get(function (req, res) {
var searchCriteria = getSearchCriteria(req.params);
Blogpost.findOne(searchCriteria, function (err, blogpost) {
if (err)
res.send(err);
res.render('pages/blogpost', {
blogpost: blogpost
})
})
})
.put(function (req, res) {
var searchCriteria = getSearchCriteria(req.params);
var updated = getBlogpostUpdate(req.body)
Blogpost.findOneAndUpdate(searchCriteria, updated, function (err, updated) {
if (err)
res.send(err);
res.json({ message: 'Blog updated.' });
});
})
.delete(function (req, res) {
var searchCriteria = getSearchCriteria(req.params);
Blogpost.findOneAndRemove(searchCriteria, function (err, removed) {
if (err)
res.send(err);
res.json({ message: 'Successfully deleted' });
});
});
//about
router.get('/about', function(req, res) {
res.render('pages/about');
});
//resume
router.get('/resume', function(req, res) {
res.render('pages/resume');
});
module.exports = router;
blogModel.js
var mongoose = require('mongoose');
var mongoosePaginate = require('mongoose-paginate');
var Schema = mongoose.Schema;
var BlogPostSchema = new Schema({
title: String,
author: String,
tagline: String,
category: String,
content: String,
tags: { type: String, lowercase: true },
date: { type: Date, default: Date.now }
});
BlogPostSchema.plugin( mongoosePaginate );
var Blogpost = mongoose.model("Blogpost", BlogPostSchema);
module.exports = mongoose.model('Blogpost', BlogPostSchema);
Your form is missing content (currently you have the name as blog-editor), author, and category fields (the last two are the <select>s but they're missing names and their <option>s are missing value attributes. Other than that you have maxlength:"160" which should probably be maxlength="160".
I'm working on creating a CRUD todo app using AngularJS, Node, Express, and MongoDB. I've got all parts figured out except for update part. I'm not really sure how to implement that or what the code might look like. Particularly the AngularJS stuff (express routing isn't so bad). I'd like it if I could update by ID. Was hoping to get some input.
function mainController($scope, $http) {
$scope.formData = {};
// when landing on the page, get all todos and show them
$http.get('/api/todos')
.success(function(data) {
$scope.todos = data;
})
.error(function(data) {
console.log('Error: ' + data);
});
// when submitting the add form, send the text to the node API
$scope.createTodo = function() {
$http.post('/api/todos', $scope.formData)
.success(function(data) {
$('input').val('');
$scope.todos = data;
})
.error(function(data) {
console.log('Error: ' + data);
});
};
// delete a todo after checking it
$scope.deleteTodo = function(id) {
$http.delete('/api/todos/' + id)
.success(function(data) {
$scope.todos = data;
})
.error(function(data) {
console.log('Error: ' + data);
});
};
Here are the routes just in case that matters.
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)
});
};
There are 2 ways - you can use $http.put bu you can also use $resource. I hope that this will help you
index.html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular-resource.min.js"></script>
<script type="text/javascript" src="angularjs_app.js"></script>
</head>
<body>
<div ng-controller="MainController">
<form name="todoForm" novalidate>
<label>Id</label>
<input type="text" name="_id" ng-model="editTodo._id">
<br/>
<label>Subject</label>
<input type="text" name="subject" ng-model="editTodo.subject">
<br/>
<label>Description</label>
<input type="text" name="desc" ng-model="editTodo.desc">
<br/>
<button ng-click="updateTodo()">Update Todo</button>
</form>
</div>
</body>
</html>
angularjs_app.js (1 Way)
var myApp = angular.module('myApp', []);
myApp.controller('MainController', ['$scope',
function($scope) {
$scope.updateTodo = function() {
$http.put('/api/todos/' + $scope.editTodo._id, $scope.editTodo).success(function() {
alert('Todo updated');
});
// Or you can try
// $http.put('/api/todos/' + $scope.editTodo._id, {"todo": $scope.editTodo})
// .success(function(data, status, headers, config){
// $scope.editTodo = data.todo;
// })
// .error(function(data, status, headers, config){
// alert(data.error_message);
// });
};
}]);
angularjs_app.js (2 Way)
var myApp = angular.module('myApp', ['ngResource', 'myAppServices']);
myApp.controller('MainController', ['$scope', 'TodoFactory',
function($scope, TodoFactory) {
$scope.updateTodo = function() {
TodoFactory.update($scope.editTodo, function() {
alert('Todo updated');
});
};
}]);
var myAppServices = angular.module('myAppServices', ['ngResource']);
myAppServices.factory('TodoFactory', ['$resource',
function($resource) {
return $resource('/api/todos/:todoId', {}, {
update: {method:'PUT', params: {todoId: '#_id'}}
});
}
]);
nodejs_server.js
var express = require('express');
var path = require('path');
var http = require('http');
var todos = require('./routes_todos');
var app = express();
app.configure(function() {
app.set('port', process.env.PORT || 3000);
app.use(express.logger('dev')); /* 'default', 'short', 'tiny', 'dev' */
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
});
app.get('/api/todos', todos.findAll);
app.get('/api/todos/:id', todos.findById);
app.post('/api/todos', todos.add);
app.put('/api/todos/:id', todos.update);
app.delete('/api/todos/:id', todos.remove);
http.createServer(app).listen(app.get('port'), function() {
console.log("Express server listening on port " + app.get('port'));
});
routes_todos.js
var mongo = require('mongodb');
var Server = mongo.Server;
var Db = mongo.Db;
var BSON = mongo.BSONPure;
var server = new Server('localhost', 27017, {auto_reconnect: true});
db = new Db('todosdb', server);
db.open(function(err, db) {
if (!err) {
console.log("Connected to 'todosdb' database");
db.collection('todos', {strict: true}, function(err, collection) {
if (err) {
console.log("Error todos does not exist");
}
});
}
});
exports.findAll = function(req, res) {
db.collection('todos', function(err, collection) {
collection.find().toArray(function(err, items) {
console.log('todos send from DB');
res.send(items);
});
});
};
exports.findById = function(req, res) {
var id = req.params.id;
console.log('Retrieving todo: ' + id);
db.collection('todos', function(err, collection) {
collection.findOne({'_id': new BSON.ObjectID(id)}, function(err, item) {
res.send(item);
});
});
};
exports.add = function(req, res) {
var todo = req.body;
console.log('Adding todo: ' + JSON.stringify(todo));
db.collection('todos', function(err, collection) {
collection.insert(todo, {safe: true}, function(err, result) {
if (err) {
res.send({'error': 'An error has occurred'});
} else {
console.log('Success: ' + JSON.stringify(result[0]));
res.send(result[0]);
}
});
});
};
exports.update = function(req, res) {
var id = req.params.id;
var todo = req.body;
console.log('Updating todo: ' + id);
console.log(JSON.stringify(todo));
delete todo._id;
db.collection('todos', function(err, collection) {
collection.update({'_id': new BSON.ObjectID(id)}, todo, {safe: true}, function(err, result) {
if (err) {
console.log('Error updating todo: ' + err);
res.send({'error': 'An error has occurred'});
} else {
console.log('' + result + ' document(s) updated');
res.send(todo);
}
});
});
};
exports.remove = function(req, res) {
var id = req.params.id;
console.log('Removing todo: ' + id);
db.collection('todos', function(err, collection) {
collection.remove({'_id': new BSON.ObjectID(id)}, {safe: true}, function(err, result) {
if (err) {
res.send({'error': 'An error has occurred - ' + err});
} else {
console.log('' + result + ' document(s) removed');
res.send(req.body);
}
});
});
};