无法获取我的数据库(MongoDB)的数据输出在我的网站上

我试图从我的mongoDB数据库中获取数据。 并输出他们在一个简单的网站,不能弄清楚如何。 当我使用直接input到contactlist数组中的“虚拟数据”时,我得到了它的工作。 而只是取而代之。

但现在我有简单的数据库,其中包括:

 [ { _id: 5880e3a737893c04c87e30bf, name: 'Tom', email: 'Tom@msn.com', number: '4444444444' }, { _id: 5880e44637893c04c87e30c0, name: 'Tracy', email: 'Tracy@asodj.com', number: '123412345' }, { _id: 5880e44637893c04c87e30c1, name: 'tucker', email: 'tucker@email.com', number: '1234456666' } ] 

server.js

 var express = require('express'); var app = express(); var mongojs = require('mongojs'); var db = mongojs('contactlist', ['contactlist']); app.use(express.static(__dirname + "/public")); app.get('/contactlist', function(req, res){ db.contactlist.find(function (err, docs) { console.log(docs); res.json(docs); }); }); app.listen(3000); console.log("Server running on port 3000"); 

controller.js:

 var myApp = angular.module('myApp', []); myApp.controller('AppCtrl', ['$scope', '$http', function($scope, $http) { $http.get('/contactlist').success(function(response){ console.log("I got the data i requested"); $scope.contactlist = response.data; }); }]); 

index.html:

 <!DOCTYPE html> <html ng-app="myApp"> <head> <title>Contact List App</title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"> </head> <body> <div class="containter" ng-controller="AppCtrl"> <h1>Contact List App</h1> <table class="table"> <thead> <tr> <th>Name</th> <th>Email</th> <th>Number</th> </tr> </thead> <tbody> <tr ng-repeat="contact in contactlist"> <td>{{contact.name}}</td> <td>{{contact.email}}</td> <td>{{contact.number}}</td> </tr> </tbody> </table> </div> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script> <script src="controllers/controller.js"></script> </body> </html> 

所以我的错误是,我的网站上的输出(如1ms): {{contact.name}} {{contact.email}} {{contact.number}}

关于加载时显示的括号,这通常是angularJS的问题。 加载/初始化需要一些时间,所以原始括号/文本在一段时间内是可见的。 完全不用担心。

在你的代码中,你直接返回db.find的结果。 从文档中, find()返回一个游标 ,而不是一个数组。 尝试这个:

 app.get('/contactlist', function(req, res){ db.contactlist.find().toArray(function (err, docs) { console.log(docs); res.json(docs); }); }); 

更新:真正的问题是在JS方面。

  $http.get('/contactlist').success(function(data) { // data is your array here ! // so data.data will be undefined... }); 

.success是一个快捷方式,但通常情况下, .get返回一个与.then使用的承诺:

 $http.get('/contactlist').then(function(response) { // here, response has a status, data and error field }); 

我强烈build议你看看这篇文章的更多信息。 另外,使用angularJS,使用$resource服务总是更干净。 这是可用的许多教程之一 。