Angularjs和nodejs的Mongodb CRUD操作 - 如果数据已存在,如何从数据库获取消息?

时间:2015-12-19 05:23:25

标签: angularjs mongoose

在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';
    }
});

1 个答案:

答案 0 :(得分:0)

  1. 在您的nodeJS路由API
  2. //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);
            }
        });
    });

    1. 将您的请求放入服务的良好做法。例如
    2. 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);
        }
      }]);