title: Using database in AngularJS - where should I write DB connection code?
body: <p>I'm now building up a web app using Node.js, AngularJS and either MySQL or MongoDB. However, when I tried to use AngularJS with a controller which includes datasets fetched from database, I wonder where I should write the code in...</p>
  
  <p>I'm now writing in the following code (search.ejs, not including full portion (such as <code>html</code> tag)):</p>
  
  <pre><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"&gt;&lt;/script&gt;
  &lt;script src="/javascripts/searchController.js"&gt;&lt;/script&gt;
  &lt;div ng-app class="row" ng-controller="searchCtrl"&gt;
  &lt;input ng-model="query"&gt;
  &lt;ul class="search"&gt;
  &lt;li ng-repeat="i in list" | filter:query"&gt;
  &lt;a href="{{i.url}}"&gt;{{i.name}}&lt;/a&gt;
  &lt;/li&gt;
  &lt;/ul&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>And I want to fetch data in <code>list</code> from database and use it. So here's <code>searchController.js</code> file:</p>
  
  <pre><code>function searchCtrl($scope){
      $scope.list = [
          {
              'name': 'Michael',
              'url': 'mic'
          },
          {
  
              'name': 'Bob',
              'url': 'bob'
          }
      ]
  }
  </code></pre>
  
  <p>However, what I want to do is instead of writing out data in the <code>$scope.list</code> variable manually, use data in database of either MySQL or MongoDB. (And MySQL is my preferred language, but MongoDB seems like the better in this case, I think.) So how can I connect to DB?</p>
  
  <p>I also have one file called <code>search.js</code>, which is the following one:</p>
  
  <pre><code>
  exports.index = function(req, res) {
      res.render("search", {
      }, function(err, res){
          res.render("index", {
              content: res
          });
      });
  }
  </code></pre>
  
  <p>And finally, I also want to hear from you whether I should first save data from database to any file and use it by opening and closing the file, or I should directly connect to database whenever the request comes to fetch data, in terms of performance and security issues, (the data in database would be updated every day, so I have to run a script to automatically recreate the served file anyway).</p>
  
  <p>Thanks.</p>