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);
});
}
});
};
Related
I have $scope.todos and in my controller the code for submitting that is
$scope.submitChanges = function() {
var todos = $resource("/todo");
//code goes here for sending variable
}
And I want to send it to Node.js , which takes it as :
router.post("/",function(req, res) {
var collection = db.get("todo");
collection.insert({ /* here comes the data to insert */ }, function(err, todos) {
if(err) throw err;
res.json(todos);
})
})
var CreditCard = $resource('/todos/:Id',
{userId:123, Id:'#id'}, {
charge: {method:'POST', params:{charge:true}}
});
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
In controller.js:
angular.module('CRUD').controller('myController',['$scope','$http', function($scope,$http){
$scope.sendData = function(){
console.log($scope.data1);
var formData = {
"username" :$scope.username,
"email" :$scope.email
};
$http({
url:'/formData',
method:'POST',
data:formData
}).success(function(data){
console.log(data);
});
}
}]).directive("myFirstDirective",function(){
return
{
template:"<b>custom directive</b>",
restrict:'E';
}
});
In your nodeJS route API
//User Schema
'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
username: String,
email: {
type: String,
unique: true //means the email has to be unique across all documents
}
});
UserSchema.path('email').validate(function(value, done) {
this.model('User').count({ email: value }, function(err, count) {
if (err) {
return done(err);
}
// If `count` is greater than zero, "invalidate"
done(!count);
});
}, 'Email already exists');
module.exports = mongoose.model('User', UserSchema);
...
//API
app.post('/formData', function(req, res){
User.create(req.body, function(err){
if (!err){
res.send(200); //user created
}
else {
if (err.name === 'ValidationError') res.send(409); //stands for form validation error
else res.send(500);
}
});
});
Good practice to put your requests in the service. For example
angular.module('CRUD').controller('myController',['$scope','$http', 'CRUDService', function($scope,$http, CRUDService){
$scope.sendData = function(){
CRUDService.createUser({
username: $scope.username,
email: $scope.email
}).then(function(res){
//all good user was created
}, function(err){
//error, failed to create user
if (err.status === 409){
//email already exists
}
});
}
}]).service('CRUDService', ['$http', function($http){
this.createUser = function(postData){
return $http.post('/formData', postData);
}
}]);
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...
});
I'm new to the stack and am building a test page to sort out my understanding before building my actual project. Right now, I'm just trying to take user input, save it to a database, and print it. The data should be saved in a basic Mongoose model, test. While all of the routes are open, instead of printing what the user entered it prints something in the following format:
{"_id":"55c3925b48b9dba0d896be40","__v":0}
I suspect it has something to do with the second line of this snippet from index.js:
router.post('/survey', function(req, res, next) {
var test = new Test(req.body);
test.save(function(err,test) {
if(err) {
return next(err);
}
res.json(test);
});
});
module.exports = router;
Relevent code:
All of index.js:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
//set up routes
var mongoose = require('mongoose');
var Test = mongoose.model('Test');
router.get('/survey', function(req, res, next) {
Test.find(function(err, tests) {
if(err) {
return next(err);
}
res.json(tests);
});
});
router.post('/survey', function(req, res, next) {
var test = new Test(req.body);
test.save(function(err,test) {
if(err) {
return next(err);
}
res.json(test);
});
});
module.exports = router;
Tests.js (model):
var mongoose = require('mongoose');
var TestSchema = new mongoose.Schema({
'name': String,
});
module.exports = mongoose.model('Test', TestSchema);
Relevant bits of angular code:
routerApp.factory('tests', ['$http', function($http){
var o = {
tests: []
};
o.getAll = function() {
return $http.get('/survey').success(function(data){
console.log('get all sees data as:' + data);
angular.copy(data, o.tests);
});
};
o.create = function(test) {
console.log('create sees test as' + test);
return $http.post('/survey', test).success(function(data){
o.tests.push(data);
console.log('Data:' + data);
});
};
return o;
}]);
routerApp.controller('FormCtrl', ['$scope', 'tests',
function($scope, tests){
$scope.test = tests.tests;
$scope.addTest = function(){
if(!$scope.text || $scope.text === '') { return; }
tests.create({
name: $scope.text
});
$scope.text = '';
};
}
]);
I suspect this is a matter of not understanding what kind of object req is, but I'm not entirely positive. How would I go about making this code save data in the format described in the mongoose model?
If you call .toObject() on the document object (res.json(test.toObject())), you should get a plain object back containing the data in that document.
Try to console.log(req.body). If it's empty, then try adding app.use(bodyParser.json()) somewhere before your routes are defined (and be sure to install it with npm and require it first).
When you POST some sort of JSON, it isn't available in req.body by default. You need bodyParser to parse the incoming data and make it available in req.body. See https://medium.com/#adamzerner/how-bodyparser-works-247897a93b90 for more info.