简体   繁体   中英

Understand communication between node angular express and mongo

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?

I would start by having a look at mean.io and scaffolding a new package and use that as a way to learn/understand communication along the stack. Essentially you will have a full working mean project and you can disect that as part of the learning process

You can also look how the articles are created how the data is saved into mongodb

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM