Angular Put Method - angularjs

I'm trying to do an Angular update using $http.put. The data is successfully passes from the form to the client controller when I do console.log, but when I do $http.put request. It comes back as PUT http://localhost:3000/articles 500 (Internal Server Error).
This is the client side articles.controller.js:
$scope.updateArticle = function(){
var data = {
id: $routeParams.id,
title: $scope.article.title,
body: $scope.article.body,
category: $scope.article.category
}
console.log(data);
$http.put('/articles', data).success(function(data, status){
console.log('abc');
});
$location.path('/articles');
}
This is the server side route for articles.js:
router.put('/', function(req, res, next){
var id = req.body.id;
var data = {
title: req.body.title,
category: req.body.category,
body: req.body.body
};
Article.updateArticle(id, data, function(err, article){
if(err){
console.log(err);
}
res.location('/articles');
res.redirect('/articles');
});
});
And this is the model article.js:
module.exports.updateArticle = function(id, data, callback){
var title = data.title;
var body = data.body;
var category = data.category;
var query = {_id: id};
Article.findById(id, function(err, article){
if(!article){
return next(new Error('Could not load article'));
} else {
article.title = title;
article.body = body;
article.category = category;
article.save(callback);
}
})
}

Why don't you try making a router.put route that targets "/articles" directly? Your articles.js file should look like this:
router.put('/articles', function(req, res, next){
console.log("Hit my route!");
//etc...
});

Related

How to query mongodb on a specific field

I have a collection of objects with the following schema :
var Meetup = new Schema({
name: String,
text:String,
});
I would like to get all of the meetups whom name contain a string.
Here is my api :
module.exports.list = function (req, res) {
Meetup.find({}, function (err, results) {
res.json(results);
});
}
and in my angular controller i have :
var Meetup = $resource('/api/meetups');
$scope.meetups = []
Meetup.query(function (results) {
$scope.meetups = results;
});
can anyone help
Query on specific field
ModelName.find({fieldName: value}, function (err, results) {
//...
});
so for your case query will be like:
exports.list = function (req, res) {
Meetup.find({name: req.query.name}, function (err, results) {
res.json(results);
});
};
and angular controller like
var Meetup = $resource('/api/meetups', {}, {
query: {method: 'get', isArray: true}
});
$scope.meetups = []
Meetup.query({name: 'yourName'}).$promise.then(function(results) {
// console.log(results);
$scope.meetups = results;
}, function(error) {
// console.log(error);
$scope.meetups = [];
});

I want to write data to mongodb Database using node.js

Right now i am writing data to json file and getting that back to html page to display. Now i want to do same with mongodb Database. I have tried something but, it doesn't working.
app.get('/', function(req, res){
url = 'http://www.amazon.in/Sony-Xperia-Z3-Copper-32GB/dp/B010V448ZC/ref=pd_rhf_se_s_cp_6?ie=UTF8&dpID=419rmomR%2BjL&dpSrc=sims&preST=_SL500_SR135%2C135_&refRID=19RT23W7T48Z99XNT6GK';
request(url, function(error, response, html){
if (!error) {
var $ = cheerio.load(html)
var json = {Product_Name : "", Brand : "", Color : "", Image : "", Price : "", Rating : ""};
var P_name = $('#title').children().text();
var brand = $('#brand').text();
var color = $('.a-row').find('span.selection').text();
var price = $('#price').find('span.a-size-medium').text();
var rating = $('#averageCustomerReviews').find('span.a-icon-alt').text();
var image = $('.imgTagWrapper').children().attr('src');
/*json.Product_Name = P_name;
json.Brand = brand.trim();
json.Color = color.trim();
json.Price = price.trim();
json.Rating = rating.trim();
json.Image = image.trim();
fs.writeFile('output.json', JSON.stringify(json, null, 4), function(err){
console.log('File successfully written! - Check your project directory for the output.json file');
})*/
var insertDocument = function(db, callback) {
db.collection('proInfo').insertOne( {
"Product_Name": P_name,
"Brand":brand,
"Color":color,
"Price":price,
"Rating":rating,
"Image":image
}, function(err, result) {
assert.equal(err, null);
console.log("Inserted a document into the proInfo collection.");
callback(result);
});
};
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
insertDocument(db, function() {
db.close();
});
});
res.send('Check your console!')
} else {
console.log("We’ve encountered an error: " + error);
}
})
})
It shows some error in console.log
D:\Hemanth\Node Js\web scraper\node_modules\mongodb\lib\url_parser.js:20
throw new Error('invalid schema, expected mongodb');
^
Error: invalid schema, expected mongodb
at module.exports
Can anybody help me to fix this issue?
Use module export in your node js routes and define the method inside the module.export as mentioned below :
module.export {}
and then call the method, apply routes in the server.js under node application :
erc(app,
{
controllers: __dirname + '/routes',
routes:{'/methodnametobecalled': { action: 'routesfilename#methodname'}
}
});
Initialize Mongoose and Schema
var mongoose = require('mongoose');
mongoose.connect('mongodb://YOURVALUES.mongolab.com:11111/NAME');
var schema = new mongoose.Schema({ name: 'string', account: 'string', date: 'string' });
var accountz = mongoose.model('accountz', schema);
Create
var small = new accountz({
name: "SAMZ",
account: "Monthly",
date: "29/12/2015"
});
small.save(function (err) {
if (err){
console.log("Error in Save");
}else{
console.log("Save Sucessfully");
}
});
Read
accountz.find().exec(function(err, data){
if (err){
console.log("Error in Reading");
}else{
console.log("The value = " + data);
}
});
Update
accountz.findOne({ "_id": "0023"}, function (err, doc){
doc.name = editObj.name;
doc.account = editObj.account;
doc.date = editObj.date;
doc.save(function (err) {
if (err){
console.log("Error in Updating");
}else{
console.log("Updated Sucessfully");
}
});
});
Delete
accountz.remove({ "_id": "0023"}).exec(function(err, data){
if (err){
console.log("Error in Deleting");
}else{
console.log("Deleting Sucessfully");
}
});
Ref This link https://shiyamexperience.wordpress.com/2015/12/29/mongodb-crud-using-mongoose/

How to retrieve mongodb data from server (node.js) to my AngularJS Route

This is my Server.js file (NodeJS):
var express = require('express');
var server= require('http');
var path= require("path");
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var app= express();
var staticDIR = path.resolve(__dirname, "./www");``
app.use(express.static(staticDIR));
app.use(bodyParser.json());
app.get("*", function (req, res) {
var indexViewPath = path.resolve(__dirname, "./www/index.html");
res.sendFile(indexViewPath);
});
var dbURI = 'mongodb://localhost:27017/mydatabase';
mongoose.connect(dbURI);
mongoose.connection.on('connected', function () {
console.log('Mongoose connected to ' + dbURI);
});
mongoose.connection.on('error',function (err) {
console.log('Mongoose connection error: ' + err);
});
mongoose.connection.on('disconnected', function () {
console.log('Mongoose disconnected');
});
process.on('SIGINT', function() {
mongoose.connection.close(function () {
console.log('Mongoose disconnected through app termination');
process.exit(0);
});
});
var userSchema = new mongoose.Schema({
name: String,
password:String,
email: {type: String, unique:true},
createdOn: { type: Date, default: Date.now }
//modifiedOn: Date,
//lastLogin: Date
});
mongoose.model( 'User', userSchema );
var User = mongoose.model('User');
var CompanySchema = new mongoose.Schema({
CompanyName: String,
password:String,
email: {type: String, unique:true},
createdOn: { type: Date, default: Date.now }
//modifiedOn: Date,
//lastLogin: Date
});
mongoose.model( 'company', userSchema );
var company = mongoose.model('company');
User.find({}, function(err, users) {
if(!err){
console.log(users);
}
});
company.find({}, function(err, users) {
if(!err){
console.log(users);
}
});
app.post('/account', function(req, res){
new company({
CompanyName:req.body.Company,
email:req.body.email,
password:req.body.password
}).save(function(err,doc){
if(err)res.json(err);
else res.send("succesfully inserted");
console.log(res);
});
});
This is my Middleware to get tha data:
app.get('/details', function (req, res) {
console.log('I received a GET request');
company.find({}, function(err, users) {
if(!err){
console.log(users);
}
else{
res.render('/details',{users:docs})
}
});
});
app.listen(9000);
console.log("Server Running on port 3000");
This is my Controller.js (AngularJS) file:
angular.module('myApp', ['ngMaterial','firebase','ui.router'])
.controller('detailsCtrl', function($scope,myfirebaseAddress,$location,$timeout) {
var ref = new Firebase(myfirebaseAddress);
})
This is my route where I want to show the mongoDb saved data
<ui-view>
<div class="sub-header">
<h3>Company Details</h3>
</div>
<ul>
<li ng-repeat="users in user">
{{user.email}}
</li>
</ul>
</ui-view>
Thanks in advance
instead if writing below code
if(!err){
console.log(users);
}
else{
res.render('/details',{users:docs})
}
do like this
if(!err){
res.send(users);
}
else{
res.send('could not retrived data');
}
in controller side you can get your all data inside success call back function.here also check
app.listen(9000);
console.log("Server Running on port 3000");
this should like below.
app.listen(9000);
console.log("Server Running on port 9000");
Controller to get the requested data
.controller('detailsCtrl', function($scope,$http) {
$scope.users = [];
$http.get('/details').then(function(d)
{
console.log(d);
$scope.users= d.data;
},function(err)
{
console.log(err); }
)
})
server route
app.get('/details', function (req, res) {
console.log('I received a GET request');
company.find({}, function(err, users) {
if(!err){
res.json(users);
}
});
});
If you want to retrieve your data, you must stop this:
res.render('/details',{users:docs})
If you want to serve data with an angular app, you have to stop to render a view and start to give back a json in your response.
res.jsonp(users)
Then you've to adjust your controller.
Write a service like:
angular.module('yourApp')
.service('userService', function($http){
return {
getUsers: function(url) {
return $http.get(url)
}
}
})
this should return an http promise.
In your controller you handle this promise this way:
$scope.users = function(){
userService.getUsers('/users')
.then(function(users){
//You have your users object
})
}
remember to handle the unsuccesfull case of your promise
Try to use the angular http module to get the node/express response that get the data from mongodb in client side; like this: https://github.com/J-Alex/api_rest_mvc

how to post http req with multiple param in angularjs,mongoose

In the view html page there is a form with a table and when i submit the form two objects are created cvm and schedules for form and table. i somehow want schedules(which is an array) to be related to cvm form. so i tried this way...
Here is the defined model
$scope.addSchedule=function(schedule)
{
console.log(schedule.startDate);
console.log(schedule.location);
$scope.schedules.push({
startDate: schedule.startDate,
location: schedule.location
});
schedule.startDate='';
schedule.location='';
};
var inData={'cvm': $scope.cvm,'schedules': $scope.schedules};
$scope.addCvm=function()
{
console.log($scope.cvm);
console.log($scope.schedules);
$http.post('/cvmApi',inData).success(function(response) {
console.log(response);
refresh();
});
};
sever side Connection
i guess somthing i missed in this part
/* POST */
router.post('/', function(req, res, next)
{
console.log("Cvm api post '/'");
console.log("retrieving:: " + req.body);
cvmModel.create(req.body, function (err, post) {
console.log("saving:: " + post);
if (err) return next(err);
res.json(post);
});
});
Here is my schema for mongodb
'use strict';
var mongoose = require('mongoose');
var cvmSchema = new mongoose.Schema({
visitOrganization: { type: String },
visitAgenda: { type: String },
accountManager: { type: String },
visitCoordinator: { type: String },
schedules:[{
startDate: String,
location: String
}]
});
module.exports = mongoose.model('visit', cvmSchema);
plz help !! thanks in advance
I think you should try with below change :
//Change addCvm function
$scope.addCvm = function(){
var inData = $scope.cvm;
inData.schedules = $scope.schedules;
console.log(inData);
$http.post('/cvmApi',inData).success(function(response) {
console.log(response);
refresh();
});
};
// Server Side API Code
router.post('/cvmApi', function(req, res, next) {
console.log("Cvm api post '/'");
console.log("retrieving:: " + req.body);
cvmModel.create(req.body, function (err, post) {
console.log("saving:: " + post);
if (err) return next(err);
res.json(post);
});
});
The thing is i dint realize my variable startDate was not in type string in my html page as i was using some date plugins....
soo ya thats it worked brilliantly ...
addCvm function in controller thanks to rana ;-)
$scope.schedules=[];
$scope.addCvm = function(){
var inData = $scope.cvm;
inData.schedules = $scope.schedules;
console.log(inData);
$http.post('/cvmApi',inData).success(function(response) {
console.log(response);
refresh();
});
};
server side Api
router.post('/', function(req, res, next) {
console.log("Cvm api post '/'");
console.log("retrieving:: " + req.body);
cvmModel.create(req.body, function (err, post) {
console.log("saving:: " + post);
if (err) return next(err);
res.json(post);
});
});
may be not required but i changed my schema though....
var cvmSchema = new mongoose.Schema({
visitOrganization: { type: String },
visitAgenda: { type: String },
accountManager: { type: String },
visitCoordinator: { type: String },
schedules: [{
dateStart: { type:String },
locationHere: { type: String }
}]
});

grab followers from mongoose schema

Basically I have a User schema. Within the schema I have the following item which contains the id's of all users. The user follows inside an array.
followers: [{
type: String,
required: false,
unique: false
}],
My question is: how do I get all the results from the followers array only so I can run a ng-repeat with them?
This is what I have tried.
Get Followers controller:
(function(){
angular.module('Scrimbox')
.controller('GetFollowingController'
, ['$scope', '$http', 'User', '$routeParams', '$location'
, function( $scope, $http, User, $routeParams, $location){
$scope.following = function(){
//Empty object to send to server
var request = {};
//get follower id
var FollowerId = $routeParams.id;
//bundle into the object to send to server
var request = {
follower: FollowerId
};
//send to server
$http.post('api/social/getfollowing', request)
.success(function(response){
console.log(response);
$scope.following = response.following;
}).error(function(error){
console.log(error);
});
};
$scope.following();
}]);
}());
getfollowing on the server:
var mongoose = require('mongoose');
var User = require('../../models/UserModel');
module.exports.getfollowing = function(req, res){
var thefollower = req.body.follower;
User.findOne({ _id: thefollower }).populate('_following').exec(function (err, user) {
if (err) {
console.log(err);
res.json(err);
} else {
console.log(user);
res.jsonp(user);
}
})
};
Called using:
app.post('/api/social/getfollowing', getfollowingController.getfollowing);
This is the response I get from the server:
But how do I only get all the ids from the following array?
Then how do I use them for a ng-repeat?
ok i did get this thanks for the responses.
i had to query the mongoDB for the user then create a variable for the followee's ID's then run a forEach Loop over all the IDs
var mongoose = require('mongoose'),
User = require('../../models/UserModel'),
async = require('async');
module.exports.getfollowing = function(req, res){
//grab the Users ID from the body
var thefollower = req.body.follower;
//create empty array that i want to populate with the followee's ID and Avatar url
var obj = [];
//query mongo for the user
User.findOne({ _id: thefollower }, function (err, user) {
if (err) {
console.log(err);
res.json(err);
} else {
//grab the following element of the users mongo schema -- should return all the followee's ID's -- tested works
var following = user.following;
//iritate throught all the followee's
async.forEach(following, function(item, callback) {
//current followee
var user = item;
//query mongo for the followee
User.findOne({_id: user}, function(err, followee, callback){
//get followee's ID and Avatar url
var id = followee._id;
var avatar = followee.avatar;
//add the followee's ID and Avatar url to the obj array
obj.push({
id: id,
avatar: avatar
});
});
//see if this worked - returns empty
console.log(obj);
callback();
}, function(err) {
//see if this worked - returns empty
console.log(obj);
//respond to the client - returns empty
res.json(obj);
});
}
});
};

Resources