2016-12-13 32 views
0

我需要一個學校項目的幫助。我正在製作一個應用程序來創建和更新需要解決的問題列表。使用MEAN存儲數據

我有一個輸入字段,我應該插入問題,然後它應該生成一個ID,狀態「打開」和日期戳。

然後問題會出現在我的輸出表中。我已經解決了,我可以顯示數據庫中的內容。現在我需要解決存儲新數據的部分。

我的計劃是用ng-點擊我的按鈕AddIssue並調用一個名爲AddIssue的函數。然後使用$ HTTP POST發送數據槽,然後用moongose存儲數據

HTML

<div ng-controller="inputCtrl"> 
<p>New issue <input class="form-control" type="text" ng-model="newIssue"></p> 
<button ng-click="AddIssue()"> Add </button> 
</div> 

<div ng-controller="tableCtrl"> 
<table class="table table-striped"> 
<thead> 
    <tr> 
    <th>Status</th> 
    <th>Issue</th> 
    <th>Date</th> 
    <th>ID</th> 
    </tr> 
</thead> 
<tbody> 
    <tr ng-repeat="issue in issueList"> 
     <td>{{issue.status}}</td> 
     <td>{{issue.issue}}</td> 
     <td>{{issue.date}}</td> 
     <td>{{issue.id}}</td> 
    </tr> 
</tbody> 
</table> 
</div> 

我的JS文件controller.js

var myApp = angular.module('myApp', []); 

// Controller for input 
myApp.controller('inputCtrl', function($scope) { 

// Call function when click on AddIssue btn 
$scope.AddIssue = function() { 

    console.log("Click click....") 

    // Use Post to send data to database  
    $http.post('/issueList').sucess(function(response){ 
     $scope.newIssue = 'New issue'; 
    }) 


} 

}); // End of input 

服務器。 js

/* Connect to db issues */ 
mongoose.Promise = global.Promise; 
mongoose.connect('mongodb://localhost/issues'); 

var db = mongoose.connection; 
db.on('error', console.error.bind(console, 'connection error:')); 

/* Connect to MongoDB */ 
db.once('open', function (callback) { 
console.log("Connected to db"); 

// Created b-schema 
issueSchema = mongoose.Schema({ 
    id: String, 
    issue: String, 
    date: String, 
    status: String 
}); 

// Create Model 
Issue = mongoose.model('Issue', issueSchema); 

這是迄今爲止,我都來了,現在我需要首先幫助如何從controller.js數據發送到server.js

其次用貓鼬來存儲它在我的MongoDB發出

+0

我想你應該看一些例子來幫助你。這是一篇關於使用MEAN堆棧創建todo應用的好文章:https://scotch.io/tutorials/creating-a-single-page-todo-app-with-node-and-angular。 –

回答

0

你需要在你的server.js中爲你的POST定義一個路由,並在裏面你可以用mongodb保存你的問題對象。

喜歡的東西:

//addIssue 
    app.post('/addIssue', function(request, response) { 
     var issue = new Issue({ 
      id: request.body.id, 
      issue: request.body.issue, 
      date: request.body.date, 
      status: request.body.status 
     }); 

     return issue.save(function(err) { 
      if(!err) { 
       return response.send(issue); 
      } else { 
       console.log("ERROR adding issue:" + err); 
      } 
     }); 
    }); 

您需要安裝一些NPM包了。例如:

  • 體解析器(NPM安裝體的解析器)
  • 快遞(NPM安裝快車)

還需要導入在你的server.js文件中使用:

var express = require('express'); 
var bodyParser = require ('body-parser'); 

這只是一個例子來澄清這個想法。在生產環境中,情況有些不同。

看看: https://scotch.io/tutorials/setting-up-a-mean-stack-single-page-application

+0

謝謝!我會嘗試這個解決方案,並與該想法合作 – mackeemackee

+0

你知道爲什麼即將獲得iss​​ueSchema不是一個函數嗎? – mackeemackee

+0

是的。我的錯!對不起,我已經更新了答案。 – deChristo