3

我正在尝试在猫鼬文档中返回 JSON 数据,然后使用 Angular 显示它。使用此代码时页面上没有错误。Angular IndexCtrl 中的 $http.get 方法从未成功,这让我相信问题在于我如何实现 API get 方法。任何帮助重写该方法以正确返回非常感谢!

澄清一下:我想要的是能够像 JSON 对象一样访问文档,这样我就可以向客户端显示数据。

更新:它确实产生了错误:

GET http://localhost:3000/api/tracks

该错误需要一段时间才能在控制台中显示

api方法

app.get("/api/tracks", function(req, res) {
return Track.find({}, function (err, tracks) {
  if (err) {
    res.send(500);
    return;
  }
   return res.json({
  tracks: tracks
    });
  });
});

猫鼬数据库

var mongoose = require('mongoose');

var uristring = 
  process.env.MONGOLAB_URI || 
  'mongodb://localhost/HelloMongoose';

var mongoOptions = { db: { safe: true }};

var db = mongoose.createConnection(uristring, mongoOptions, function (err, res) {
      if (err) { 
        console.log ('ERROR connecting to: ' + uristring + '. ' + err);
      } else {
        console.log ('Succeeded connected to: ' + uristring);
      }
  });

//a Schema for a track
var Schema = new mongoose.Schema({
  name: String,
  location: String,
  description: String
});

var Track = mongoose.model('Track', Schema);

var spot = new Track({name: 'zildjian'});
spot.save(function (err) {
  console.log('saved');
  if (err) // ...
  console.log('meow');
});

角控制器

function IndexCtrl($scope, $http) {
  $http.get('/api/tracks').
    success(function(data, status, headers, config) {
      $scope.tracks = data.tracks;
      console.log($scope.tracks + "scope tracks data");  //This does not log! it never makes it this far
    });

}

显示 $scope.tracks 的 Jade 模板

p There are {{tracks.length}} posts

div(ng-repeat='track in tracks')
  h3 {{track.name}}
  div {{track.description}}
4

1 回答 1

3

我没有正确地从模型中提取条目。这是我修复它的方法:

app.get("/api/tracks", function (req, res) {
var track = [];

var Track = mongoose.model('Track', trackSchema);
  Track.find({}, function (err, records) {
    records.forEach(function (post, i) {
      track.push({
        id: i,
        title: post.title,
        text: post.text.substr(0, 50) + '...'
      });
    });
    res.json({
      track: track
    });
  });
};
}
于 2012-12-27T08:06:57.063 回答