I'm trying to understand the communication in a MEAN stack.
I wrote the following pieces of code, using yeoman fullstack generator to scaffolding the app:
- mongoose schema
'use strict';
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var StuffSchema = new Schema({
name: String,
});
mongoose.model('Stuff', StuffSchema);
- code to save on mongodb
'use strict';
var mongoose = require('mongoose'),
Stuff = mongoose.model('Stuff');
exports.create = function(req, res, next){
var newStuff = new Stuff(req.body);
newStuff.save(function(err){
if (err) return res.json(400, err);
})
res.send(newStuff);
}
- node routes
'use strict'
var stuff = require('./controllers/stuff'),
module.exports = function(app) {
app.route('/api/stuffs')
.post(stuff.create);
}
- angular service
'use strict';
angular.module('ngStuff').factory('Stuff', function ($resource) {
return $resource('/api/stuffs/');
});
- angular controller
'use strict';
angular.module('ngStuff').controller('StuffCtrl', function($scope, $location, Stuff){
$scope.stuff = {};
$scope.add = function(){
var stuff = new Stuff({name: $scope.stuff.name});
stuff.$save(function(response){
$location.path('#/');
});
$scope.stuff.name = "";
}
});
Now, I'm able to save document on mongodb, but the location don't change. Is this the correct way to connect all together? Is there a better way to do that? Should I write the save function in an angular service instead of an angular controller?