[英]How can I save data from a form to a Mongodb database?
作为一个项目,我试图转换待办事项应用程序以将待办事项保存在mongdb数据库中,而不是json文件中。 因此,我设置了后端,并更改了我的角度功能以向后端发出请求,但现在遇到了一些问题。
这是我的server.js文件:
//connect to database
mongoose.connect('mongodb://localhost:27017/myTodoApp');
// set static files location
// used for requests that our frontend will make
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
//define our model for the todos
var Todo = mongoose.model('Todo', {
name: String,
});
//when I get a get request I'm going to send
//the index.html file
app.get('/', function(req, res){
res.sendFile( __dirname + '/public/index.html');
});
//get all the todos from the database
app.get('/api/todos', function(req, res){
Todo.find(function(err, todos){
if(err)
res.send(err)
res.json(todos);
});
});
//create a todo
app.post('/api/todos', function(req,res){
Todo.create({
name: req.body.text,
checked: false
}, function(err, todo){
if(err)
res.send(err);
Todo.find(function(err, todos){
if(err)
res.send(err)
res.json(todos);
});
});
});
app.delete('/api/todos/:todo_id', function(req, res){
Todo.remove({
_id: req.params.todo_id
}, function(err, todo){
if(err)
res.send(err);
Todo.find(function(err, todos){
if(err)
res.send(err);
res.json(todos);
});
});
});
app.listen(3000);
这是我将前端连接到后端的控制器:
var app = angular.module('myApp', ['navigationDirective']);
app.controller('MainController', ['$scope','$http', function($scope, $http){
$scope.formData = {};
//return the data from the json file
$scope.loadData = function(){
$http.get('/api/todos')
.then(function(data){
$scope.todos = data;
console.log(data);
})
};
//call the loadData function that returns the data from the json file
$scope.loadData();
$scope.addTodo = function() {
$http.post('/api/todos', $scope.formData)
.success(function(data) {
$scope.formData = {}; // clear the form so our user is ready to enter another
$scope.todos = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
};
/*$scope.addTodo = function(){
$scope.todos.push({name: $scope.newTodo, checked: false});
$scope.updateData({name: $scope.newTodo, checked: false});
$scope.newTodo = '';
console.log('Works');
};*/
}]);
关于我在做什么错的任何想法?
我将用于此问题的主要文件上传到plunkr
如果要保存更多字段,则需要在Todo Model Schema中定义它们。 如果未定义该字段,Mongoose将不会保存它。
var Todo = mongoose.model('Todo', {
name: String,
checked: Boolean,
date: {
type: Date,
default: Date.now
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.