我试图从我的mongoDB数据库中获取数据。并将它们输出到一个简单的网站上,但无法弄清楚如何。当我使用"虚拟数据时,我得到它的工作"我直接输入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}}
答案 0 :(得分:1)
关于加载时显示的括号,这通常是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
});
我强烈建议您查看this article以获取更多信息。此外,使用angularJS,使用$resource
服务总是更干净。这是one of the many tutorials available。