What could be the reason behind receiving information from a mongodb database that seems to be empty?

I have been working on a todo application, and I am facing an issue with the ng-repeat directive in my code. It seems to create five todo boxes even when the database is empty. This may be related to the loadData function that I am calling, but I am unable to pinpoint the exact cause. You can view a screenshot of how it appears in my browser along with debugger data here. Upon making a GET request to localhost:3000/api/todos, I receive [], indicating that the database is indeed empty. Any suggestions or insights?

Here is a snippet from my html file:

<div class="row">
  <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="formData.newTodo" required>
    <button ng-click="addTodo(formData)">Add</button>
  </form>
</div>

This is my controller:

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

app.controller('MainController', ['$scope','$http', function($scope, $http){
  $scope.formData = {};

$scope.loadData = function(){
  $http.get('/api/todos')
    .then(function(data){
      console.log('Data:' + data);
      $scope.todos = data;
    });
};
//call the loadData function that returns the data from the json file
$scope.loadData();

//Add a new todo to the database
$scope.addTodo = function(){
  $scope.formData = {
    name: $scope.formData.newTodo
  };
  $http.post('/api/todos', $scope.formData)
    .then(function(data){
      console.log($scope.formData.name);
      $scope.todos = data;
      $scope.formData = {};
      console.log(data);
    });
}

}]);

and here is my server.js file:

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

//connect to database
mongoose.connect('mongodb://localhost:27017/tododbtest');

// set static files location
// used for requests that our frontend will make
app.use(express.static(__dirname + '/public'));

//app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
//define our model for the todos
var Todo = mongoose.model('Todo', {
  name: String,
  //maybe change it to bool later
  //checked: boolean
});

//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)
    console.log(todos);
    res.json(todos);
  });
});

//create a todo
app.post('/api/todos', function(req, res){
  console.log("Req.body.name:" + req.body.name);
  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);
    });
  });
});

app.listen(3000);

Answer №1

Utilizing the $http service will result in a promise that resolves to a response object. Within this object, the property Data is crucial. Assign response.data to the todos variable.

  $http.post('/api/todos', $scope.formData)
    .then(function(response){
      console.log($scope.formData.name);
      $scope.todos = response.data;
      $scope.formData = {};
    });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can anyone identify the problem with this Angular Js sample code?

I recently started learning angularJS and decided to create a calculator using this framework. The calculator consists of two combo boxes for input values and another combo box for selecting the operation to be performed. However, upon clicking the button, ...

Beginner: Interested in creating a web application with HTML, CSS, AngularJS, NodeJS, and MySQL?

After extensive searching on the internet, I have yet to come across a definitive answer. I am in the early stages of developing a web application and want to ensure that I am using the correct languages before diving too deep into it. Currently, my plan ...

Modifying the information depending on the option chosen from the dropdown menu using angularJS

I have a dropdown menu where I can choose between two options, and when selected, the corresponding data is displayed. However, I would like to display the data that is inside a div tag instead. Check out this Fiddle Demo HTML: <div ng-controller="Ct ...

Switching from the .html extension to the absence of .html in Angular

I currently have this htaccess file set up: <IfModule mod_rewrite.c> RewriteEngine on RewriteCond %{REQUEST_FILENAME} -s [OR] RewriteCond %{REQUEST_FILENAME} -l [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^.*$ - [NC,L] #R ...

Use a boolean value to determine the styling of multiple items simultaneously

I'm currently attempting to modify the appearance of the bars in each area (a total of 12), so that a value of 1 equates to true (displayed as green) and a value of 0 equates to false (displayed as red). This will dynamically change the color of each ...

What strategies can be utilized to raise the max-height from the bottom to the top?

I am facing the following coding challenge: <div id = "parent"> <div id = "button"></div> </div> There is also a dynamically generated <div id="list"></div> I have successfully implem ...

Using accent marks in AJAX to retrieve information from a database

I'm currently working on compiling a list that can be found at the following link: Within the php file, I have implemented meta tags to handle accents. However, when using ajax to display search results, entering accents such as ö,ü,ő etc in the s ...

What is the best way to eliminate the lower margin in the UI-Boostrap Angular Tab directive?

The ui.bootstrap.tabs directive, which can be found here, seems to have a default margin before displaying its content. https://i.stack.imgur.com/NECGA.png Here is the HTML snippet: <uib-tabset active="activeJustified" justified="false" id="tabSet" s ...

VueJS 3 - Issue with applying the <router-link-active> class to routes that share the same path starting name

In my navigation bar, I have created 3 links which are all declared at the root level of the router object. I've applied some simple styling to highlight the active link on the navbar using the <router-link-active> class. Everything works as exp ...

Mastering the correct way to handle the "window" object within the Node.js testing environment using JSDom

Testing my React app using Tape and JSDom involves importing a specific module at the beginning of each test JS file: import jsdom from 'jsdom' function setupDom() { if (typeof document === 'undefined') { global.document = jsdom ...

Once I have verified the user's credentials through a POST request, I will proceed to make a GET request

I am in the process of constructing a dashboard that automates logging into an API and updating specific data elements. I have successfully managed to login and authenticate, but I am unsure how to proceed with chaining the GET request after the POST actio ...

Tips for effectively eliminating errors in a redux store

Within my react-redux application, I have implemented a system to catch error responses from redux-saga. These errors are saved in the redux-store and rendered in the component. However, a major challenge arises when trying to remove these errors upon comp ...

Running JavaScript from Markdown - Dynamically generated webpage

Can JavaScript be run in a MarkdownRemark programmatically created page from .md? I want to include a photogallery from EmbedSocial, which requires a div with a specific classname and a script tag following it. This is how it looks in the .md file: <d ...

AngularJS - Highlighted row value

Here is a helpful example you can refer to: Check out the demo here: The code provided works well, but I would like to add a button. When this button is clicked, an alert should display the value of the name column - for example, "Noodles". This snippet ...

What could be causing the post method to fail in this AngularJS example?

After successfully reading a JSON file in my sample code, I encountered an issue when trying to update the JSON file. The error message "Failed to load resource: the server responded with a status of 405 (Method Not Allowed)" appeared, even though the data ...

Leveraging ES6 with jQuery in Symfony 4

Currently working on a simple app using Symfony 4 and trying to add custom triggers in JavaScript. Having trouble getting my additional code to work as expected, even though it's compiled by Webpack via encore. It seems like my event is not triggering ...

Dynamic visual content (map)

I'm currently working on creating an interactive image for my website where clicking on points A, B, C, ... N will reveal bubbles with images and text inside them. Would anyone be able to provide guidance on how to achieve this? Or direct me to resou ...

How can I prevent getting stuck in a never-ending React re-render cycle?

I always believed that placing any form of setState within a useEffect call would lead to an endless re-render loop since the useEffect gets triggered on every render. Surprisingly, in my Next.js application, everything seems to be functioning well without ...

What could be the reason that my JSON request is not functioning properly?

I am currently working on creating a movie search application. This project marks my first time delving into json and I'm facing some issues with my code. As of now, I have it set up and running smoothly on localhost through xampp. On submitting the ...

Download the latest Backand Angular SDK from npm

Currently, I have integrated the angularbknd-sdk into my Ionic 1 mobile app. I added it using Bower and then loaded it as an npm module with browserify-shym: In my package.json file "backand": "./bower_components/angularbknd-sdk/dist/backand.min.js" Aft ...