Updating mongodb in a mean stack - javascript

I want to update my mongodb I know what to write on the server side but i dont know how to use it on the client side in angular. can you help ?
here is my server side code
module.exports.updateUser = function (req, res) {
// get a user with ID of 1
User.findById(1, function(err, user) {
if (err) throw err;
// change the users location
user.location = 'uk';
// save the user
user.save(function(err) {
if (err) throw err;
console.log('User successfully updated!');
});
});
}

You need to create a rest api(/users/save)
var users = require('./src/servies/users');
app.post('/users/save', users.updateUser);
that will call your updateUser function.
In angular you can use http module something like below code
<script>
var app = angular.module("app", []);
app.controller("HttpPostController", function ($scope, $http) {
$scope.SendData = function () {
// use $.param jQuery function to serialize data from JSON
var data = $.param({
location: $scope.location
});
var config = {
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
}
// calling post /users/save api from angular code
$http.post('/users/save', data, config)
.success(function (data, status, headers, config) {
})
.error(function (data, status, header, config) {
});
};
});
</script>

Related

Asynchronous Javascript Request Issue (Node, request-promise module)

I am building an application and having an issue with making a request from the client, sending it to my server, having the server make the API call and then send the result back to the client. I am using Node and the Request-Promise module.
Here is the client side code:
$(document).ready(function() {
var artistSearch = () => {
const q = $('.artistName').val();
$.ajax({
type: "POST",
url: "http://localhost:3000/request",
data: {artist: q},
})
.done(function(data) {
console.log('data: ', data)
})
};
$(".artistSearch").submit( () => {
artistSearch();
});
});
This successfully makes a request to the server:
app.post('/request', (req, res) => {
const artist = req.body.artist;
const searchURL = "https://api.spotify.com/v1/search? q="+artist+"&type=artist";
var targetObj;
var options = {
uri: searchURL
};
rp(options)
.then(function (data) {
console.log(data);
res.send(data);
})
.then(function() {
console.log('complete');
})
.catch(function (err) {
console.log('error')
});
});
Which ultimately successfully grabs the data from the API call, but never sends it back to the client! If I do res.send() outside of my .then promise, I can receive data on the client end.
Is there something I am missing? Thanks in advance!
Try this
var options = {
uri: searchURL,
simple: false,
};
rp(options)
.then(function (data) {
console.log(data);
res.status(200).send(data).end();
})
.then(function() {
console.log('complete');
})
.catch(function (err) {
console.log('error')
});
I think the client did receive data, but the connection didn't terminate correctly as it thinks there are more data. This is because you didn't specify the header and the module http couldn't figure out the content-length.
rp(options)
.then(function (data) {
console.log(data);
// res.send(data);
// assume data is JSON.
res.setHeader (200, {'Content-Type': 'application/json',
'Content-Length':data.byteLength});
res.end(data); //Send data immediately.
})
...
If data is a string, you will need to use data.length instead. In fact, if data is a string, then by default the header is {'Content-Type': 'application/json', 'Content-Length':data.length}

Angularjs, function not being properly invoked inside controller

I'm doing this login exercise where users can login and post notes, and view the notes that they've posted. My problem is when I logout and login with a different user I see the notes from the previous user.
Here's an illustration:
I log in with a different user then this shows up:
I restart the page and the appropriate note shows up:
The controller for this:
exports.homeController = function ($scope, $location, $q, $users, $window, $notes, $http) {
var auth = function () {
var userInfo = $users.getUserInfo()
if (userInfo) {
return $q.when(userInfo)
} else {
return $q.reject({ authenticated: false })
}
}
$scope.userInfo = auth()
myNotes($scope.userInfo.$$state.value.accessToken) // I invoke my function to get the notes for each specific user but it doesn't seem to work.
$scope.logout = function () {
$users.logout()
.then(function (results) {
$scope.userInfo = null
$scope.myNotes = null
$location.path('/')
}, function (err) {
console.log(err)
})
}
$scope.notes = {
notes: ''
}
$scope.postNote = function () {
$notes.postNotes($scope.userInfo.$$state.value.accessToken, $scope.notes)
.then(function (result) {
$scope.myNotes.push($scope.notes)
$scope.notes = ''
}, function (err) {
console.log(err)
})
}
function myNotes (user_id) {
$notes.getMyNotes(user_id)
.then(function (result) {
console.log(result)
$scope.myNotes = result.data
}, function (err) {
console.log(err)
})
}
}
This is the app https://login-sys.herokuapp.com/
I've found your non-minified code for the services.
Based on that I think the problem is that you declare var deferred = $q.defer() one time in the $notes service.
I think it should be "renewed" every time the service methods are called:
function getMyNotes (user_id) {
var deferred = $q.defer();
$http.get('/api/myNotes/' + user_id + '?access_token=' + user_id)
.then(function (result) {
deferred.resolve(result)
}, function (err) {
deferred.reject(err)
});
return deferred.promise
}
Similarly in postNotes.
The second time you return the same promise with the same value, so your homeController's getMyNotes function will get the same result despite the $notes service making a new request.
In the $users service's logout and signup functions you are already using it correctly.

Upload Images through promises , bluebird pass params

I need to upload images on Amazon S3 and to store the image's links received as a response into database.
I'm using Bluebird.js. Please tell me how to pass the values recorded from one Promise to another.
Promise.resolve()
.then(function() {
var promImageLoc = [];
var upload = $scope.uploaderPromo.queue;
$scope.uploaderPromo.uploadAll();
$scope.uploaderPromo.onSuccessItem = function(fileItem, response, status, headers) {
console.log('success response', response);
var promImage = promImageLoc.push(response.location);
return promImage;
}
console.log(promImage);
})
.then(function (promImageLoc) {
console.log(promImageLoc);
})
Update: I'm begginer at MEAN stack developer and using angular-file-upload and multer to pass file from client side to server. All I need (is love) now - make entry in mongo DB with follows link. Links come in callback one after another because files are sent one by one (POST) and i have finally entry but with empty arrays. I know the reason of that but I don't know how to solve it. Here is full code of function that sent data from client.
$scope.createPromo = function () {
Promise.resolve()
.then(function() {
var promImageLoc = [];
var upload = $scope.uploaderPromo.queue;
$scope.uploaderPromo.uploadAll();
async.eachSeries(upload, function(response) {
$scope.uploaderPromo.onSuccessItem = function(fileItem, response, status, headers) {
console.log('success response', response);
return promImageLoc.push(response.location);
}
})
})
.then(function() {
var promLogoLoc = [];
$scope.uploaderLogo.uploadAll();
$scope.uploaderLogo.onSuccessItem = function(fileItem, response, status, headers) {
console.log('success response', response);
var location = response.location;
return location;
}
promLogoLoc.push(location);
return promLogoLoc;
})
.then(function (promImageLoc, promLogoLoc) {
if ($scope.promZipCode == undefined) {
$scope.promZipCode = '07946';
}
$http.post("/promo/create", {
'promName': $cookieStore.get('User').user.username + '.' + $scope.promName, //username.promotion name
'promDesc': $scope.promDesc,
'promImage': promImageLoc,
'promLock': $scope.promLock,
'promLogo': promLogoLoc,
'promLogoPos': $scope.selectPos,
'promNotice': $scope.promNotice,
'promZipCode': $scope.promZipCode, //{obj}
'promRadius': $scope.promRadius
})
.success(function (data, status) {
console.log(status);
$state.go('home.promotion.promotions');
}).error(function (err) {
$scope.isUniqError = true;
console.log('CREATE ERR', err);
});
})
.catch(function (error) {
console.log('ERROR PROMISE:', error);
})

How to create a function that returns a value fetched with $http

My Code is:
$rootScope.getResource = function(id) {
$http.get( "path/of/resource/" + id )
.success(function (data, status, header, config) {
return data;
})
.error(function (data, status, header, config) {
console.log("Error");
});
But it always returns 'undefined'.
I know the problem is the $http function is asynchronous and I should use promises, but I can't figure out how to do everything inside just a function in $rootScope.
You should return the data withing a callback.
$rootScope.getResource = function(id, callback) {
var cb = callback || angular.noop;
$http.get( "path/of/resource/" + id )
.success(function (data, status, header, config) {
return cb(data);
})
.error(function (data, status, header, config) {
console.log("Error");
return cb('error');
});
Then, to make use of the updated getResource function
$scope.assignReturnedData = $rootScope.getResource(15, function(data) {
$scope.yourVariable = data;
});
You can get the idea from this working plunker.
One side note, I wouldn't encourage you using $rootScope to get data, instead you should look into using angular service.

How to make a GET and POST request to an external API?

var Attendance = require('../../../collections/attendance').Attendance;
var moment = require('moment');
module.exports = function(app) {
app.get('/api/trackmyclass/attendance', function(req, res) {
var data = req.body;
data['user'] = req.user;
Attendance.getByUser(data, function(err, d) {
if (err) {
console.log('This is the err' + err.message);
res.json(err, 400);
} else {
var job = d['attendance'];
if (typeof job != undefined) {
res.json(job);
console.log('This is it' + job['status']);
} else
res.json('No data Present', 200);
}
});
});
app.post('/api/trackmyclass/attendance', function(req, res) {
var data = req.body;
data['user'] = req.user;
Attendance.create(data, function(err, d) {
if (err) {
console.log('This is the err' + err.message);
res.json(err, 400);
} else {
var attendance = d['attendance'];
if (typeof job != undefined) {
console.log('Attendance record created' + attendance);
res.json(attendance);
} else
res.json('No data Present', 200);
}
});
});
}
This is the api code I to which I need to make the GET and POST request. But I have no idea how to do it.
It looks like your code is using express which would normally be good for building and API for your app. However to make a simple request to a third party api and staying in node.js why not try the request module which is great. https://www.npmjs.org/package/request
Your example does not show what the path of the request is or if you need any additinal headers etc but here is a simple example of a GET request using request.
var request = require('request');
function makeCall (callback) {
// here we make a call using request module
request.get(
{ uri: 'THEPATHAND ENDPOINT YOU REQUEST,
json: true,
headers: {
'Content-Type' : 'application/x-www-form-urlencoded',
}
},
function (error, res, object) {
if (error) { return callback(error); }
if (res.statusCode != 200 ) {
return callback('statusCode');
}
callback(null, object);
}
);
}
or jquery .ajax from a front end client direcct to your path
$.ajax({
url: "pathtoyourdata",
type: "GET",
})
.done(function (data) {
//stuff with your data
});

Categories

Resources