I'm making a simple todo app. I'm using angular for the frontend and nodejs for the backend. After doing some debugging I now can post data to my mongodb database using Postman though when I do it on my website a new object is being created on the database but without the values that I've given to the object.
This is my model and how I connect to the database:
var mongoose.connect('mongodb://localhost:27017/tododb');
var Todo = mongoose.model('Todo', {
name: String });
and here is how I handle the request:
app.post('/api/todos', function(req, res){
Todo.create({name: req.body.name, checked: false},
function(err, todo){
if(err) res.send(err);
Todo.find(function(err, todos){
if(err) res.send(err);
res.json(todos);
});
});
});
I'm also using bodyparser to handle the data:
app.use(bodyParser.urlencoded({ extended: true }));
This is my function on the frontend (AngularJS):
$scope.formData = {};
$scope.addTodo = function() {
$http.post('/api/todos', $scope.formData)
.success(function(data) {
$scope.todos = data;
$scope.formData = {}; // clear the form so our user is ready to enter another
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
};
Another problem is that the $scope.formData = {} doesn't clear the input field.
And lastly this is the part of my html file that displays the todos:
<h1>Things you have to do</h1>
<li ng-repeat="todo in todos">
<p id="todobox"> {{ todo.name }} </p>
</li>
<form>
<input type="text" placeholder="I need to do..." ng-model="newTodo">
<button ng-click="addTodo()">Add</button>
</form>
This is the result I get when I visit localhost:300/api/todos
[{"_id":"57275afef11dc77b17a90eda","__v":0},
{"_id":"57275b5ef11dc77b17a90edb","name":"test from postman","__v":0}]
The first one was created from my input box by clicking the add button, the second one was created by sending a post request with Postman and telling it what the name value is.