作为一个项目,我试图转换我的todo应用程序,将todos保存在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
上传了我用于解决此问题的主要文件答案 0 :(得分:0)
如果您想保存更多字段,则需要在Todo模型Schema中定义它们。如果该字段未定义,则Mongoose不会保存它。
var Todo = mongoose.model('Todo', {
name: String,
checked: Boolean,
date: {
type: Date,
default: Date.now
}
});