除非刷新页面,否则角色对象在创建新对象后不保存或从数据库中删除

时间:2016-06-14 04:12:17

标签: javascript angularjs node.js mongodb express

这是我第一次尝试MEAN应用程序。我正在尝试创建一个将车辆存放在停车库中的应用程序,您可以在车库中编辑或删除它们。

当创建具有一些预定义值的新车辆时,我可以在客户端正确编辑和删除它们,但是当我尝试在Mongo DB中保存这些更改时,我发现了一个错误。

如果我创建一个新车辆并刷新页面,则添加车辆,然后我可以从mongo DB中正确编辑和删除它们。

这是我收到的错误代码: vendor.bundle.js:11936 PUT http://localhost:3000/api/vehicles/ $%7Bvehicle._id%7D 500(内部服务器错误)

*我非常肯定它,因为当我创建新的Vehicle它没有._Id属性但我不能手动创建,所以我很困惑如何解决这个问题所以我的帖子或删除请求失败。

<!doctype html>
<html lang="en">
<head>
  <title></title>
  <link href='https://fonts.googleapis.com/css?family=Varela+Round' rel='stylesheet' type='text/css'>
  <link rel="stylesheet" href="/styles/main.css" type="text/css">
   <!--Import Google Icon Font-->
      <link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
      <!--Import materialize.css-->
      <link type="text/css" rel="stylesheet" href="styles/css/materialize.min.css"  media="screen,projection"/>
       <link type="text/css" rel="stylesheet" href="styles/css/custom.css"  media="screen,projection"/>
        <!-- Angular Material style sheet -->
  <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/angular_material/1.1.0-rc2/angular-material.min.css">

      <!--Let browser know website is optimized for mobile-->
      <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
      <!-- Angular chart -->
      <link rel="stylesheet" href="/bower_components/angular-chart.js/dist/angular-chart.css">
    
</head>
<body ng-app="parkApp"  ng-controller="mainCtrl">
  <ng-include src="'templates/navbar.html'">
  </ng-include>
  
  <h1>Lot Status</h1>

  <div class ="container" >
  <!-- Entire Table Data -->
    <div class ="row">
    <!-- Graph Data -->
      <div  class= "col s12 md3 ">
        <canvas id="pie" class="chart chart-pie"
          chart-data="[vehicles.length,200-vehicles.length]" chart-labels="['parked','Empty Spaces']">
        </canvas> 
      </div>
      <div class= "col s12 md9 scroll">  
      <!--   Title Parked Vehicles -->
        <div class ="row">
          <div class ="col s12 md12">
            Parked Vehicles : {{vehicles.length}} </br>
            <a href="" ng-click ="addVehicle()"> Park A New Car</a>
          </div>  
        </div>  
      <!-- Column Titles  --> 
        <div class ="row ">
          <div class ="col s2 md2">
            State
          </div> 
          <div class ="col s2 md3">
            Plate
          </div>  
          <div class ="col s4 md4">
            Time
          </div>  
          <div class ="col s2 md2">
            Type
          </div>  
          <div class ="col s2 md2">
            Remove
          </div>   
        </div> 
      <!-- Vehicle Data  --> 
        <div ng-repeat ="vehicle in vehicles" class ="row border" >
          <div class ="col s2 md2 ">
            <label ng-hide ="editing" ng-click="editing = !editing">{{vehicle.state}}</label>
            <input ng-show ="editing" ng-blur ="editing = false; editVehicle(vehicle)" ng-model="vehicle.state"></input>
            
          </div> 
          <div class ="col s2 md3">
            <label ng-hide ="editing" ng-click="editing = !editing">{{vehicle.plate}}</label>
            <input ng-show ="editing" ng-blur ="editing = false; editVehicle(vehicle)" ng-model="vehicle.plate"></input>
           
          </div>  
          <div class ="col s4 md4">
            {{vehicle.time | date:'medium'}}
           
          </div>  
          <div class ="col s2 md2">
           <!--  <label ng-hide ="editing" ng-click="editing = !editing">{{vehicle.type}}</label>
            <input ng-show ="editing" ng-blur ="editing = false" ng-model="vehicle.type"></input> -->
             
       
          
            <label ng-hide ="editing" ng-click="editing = !editing">{{vehicle.type}}</label>
             <md-select ng-show ="editing" ng-blur ="editing = false" ng-change="editVehicle(vehicle)"  ng-model="vehicle.type" md-selected-text="getSelectedText()">
                <md-optgroup label="items">
                  <md-option ng-value="item" ng-repeat="item in items">{{item}}</md-option>
                </md-optgroup>
              </md-select>
      
        
          
          </div>  

          <div class ="col s2 md2">
            <a href="" ng-click="deleteVehicle(vehicle, $index)">Remove</a>
            
          </div>   
        </div> 
      </div>  
    </div>    


  </div>  

    
  <script src="/scripts/vendor.bundle.js"></script>
  <script src="bower_components/Chart.js/Chart.js"></script>
<script src="bower_components/angular-chart.js/dist/angular-chart.js"></script>
<!--   All of the apllications code -->
  <script src="/scripts/todo.bundle.js"></script>

 <!--  Materialize Javascript -->
 
   <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
    <script type="text/javascript" src="styles/js/materialize.min.js"></script>

    

     <!-- Angular Material requires Angular.js Libraries -->
  
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-animate.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-aria.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-messages.min.js"></script>

  <!-- Angular Material Library -->
  <script src="http://ajax.googleapis.com/ajax/libs/angular_material/1.1.0-rc2/angular-material.min.js"></script> 
    </body>
 
</body>
</html>

'use strict';

//for webpack
var angular = require('angular');

angular.module('parkApp')
//$q is an anguolar service used to manage request
.service('dataService', function($http, $q) {
  
//service to get the vehicle data from api response body
  this.getVehicles = function(cb){
    $http.get('api/vehicles/').then(cb);
  }

  //Save the vehicle to db as soon as it is added
  this.addVehicle = function(vehicle){
    $http.post('/api/vehicles/', vehicle);
  }

  //update the vehicle in the db
  this.updateVehicle = function(vehicle){
    $http.put('/api/vehicles/${vehicle._id}', vehicle);
  }

  // delete Vehicle from the db
  this.deleteVehicle = function(vehicle) {
    $http.delete('/api/vehicles/${vehicle._id}');

  };

  
  
});

'use strict';
//for webpack
var angular = require('angular');

angular.module('parkApp')
.controller('mainCtrl', function($scope, $interval, $log, dataService){
 

  //delete a vehicle
   $scope.deleteVehicle = function(vehicle, index) {
    if(confirm('Are you sure you want to delete this Vehicle?')){
      $scope.vehicles.splice(index, 1);
      dataService.deleteVehicle(vehicle);
   }
  };


//call get vehicles data service to set scope vehicles variable
  $scope.vehicles;
  dataService.getVehicles(function(response){
    var vehicles = response.data.vehicles;
    $scope.vehicles = vehicles;
    
  })
//Select Vehicle Types from drop down with angular-materialize-css
  $scope.items = ['Valet','Term','Regular'];
      $scope.selectedItem;
      $scope.getSelectedText = function() {
        if ($scope.selectedItem !== undefined) {
          return "You have selected: Item " + $scope.selectedItem;
        } 
        else {
          return "Type";
        }
    }

// add Vehicles to Parking Garage
$scope.addVehicle = function() {
    var vDate = new Date(); //create a new date object
   
    var vehicle = {state: "Ma",
                      type: "Valet", time:vDate, type:'Regular', plate:"123-ABC"}
    $scope.vehicles.unshift(vehicle);
    dataService.addVehicle(vehicle); //save to db

  };  

// edit vehicles in Parking Garage
$scope.editVehicle = function(vehicle){
  dataService.updateVehicle(vehicle); // update the vehicle

};

  
  
})

'use strict';

// import express with require method
var express = require('express');


// import Vehicle model
var Vehicle = require('../models/vehicle');

// express router instance
var router = express.Router();

//index api route for  getting all /vehicles
router.get('/vehicles', function(req, res){
	//find all objects in the todo model
	Vehicle.find({}, function(err, vehicles){
		if(err){
			 return res.status(500).json({message: err.message});
		}else{
			res.json({vehicles:vehicles})
			// res.send('These are Fetch park vehicles');

		}	
	});
})

//post route to create new vehicles
router.post('/vehicles', function(req,res){
	var vehicle = req.body; //set vehicle equal to post request body
	//save to mongodb
	Vehicle.create(vehicle, function(err,vehicle){
		if(err){
			return res.status(500).json({err: err.message});
		}
		//else send back json object with completed message
		res.json({'vehicle':vehicle, message: 'Car Parked'});
	})
});

//Put route to update existing vehicles
router.put('/vehicles/:id',function(req,res){
	var id = req.params.id; //find id by url params id key
	var vehicle = req.body; // vehicle is request body

	if(vehicle && vehicle._id !== id){
		return res.status(500).json({err: "Ids dont match!"})
	}
	//else find by id and update with new data
	Vehicle.findByIdAndUpdate(id,vehicle,{new:true},function(err,vehicle){
		if(err){
			return res.status(500).json({err: err.message});
		}
		// respond back with json object and message updated
		res.json({'vehicle': vehicle, message:'Vehicle Updated'})
	})
});
//delete route to destroy vehicle in database
router.delete('/vehicles/:id',function(req,res){
	
	var id = req.params.id;
	// var vehicle = req.body;

	
	Vehicle.findByIdAndRemove(id,'select', function(err){
		if(err){
			return res.status(500).json({err: err.message});
		}
		res.json({'vehicle with':id, message:'Was Deleted'})

	}); 
})




//export router to use in app.js
module.exports = router;

0 个答案:

没有答案