2012-12-27 72 views
3

我試圖在一個mongoose文檔中返回JSON數據,然後使用Angular顯示它。使用此代碼時頁面上沒有錯誤。 Angular IndexCtrl中的$ http.get方法從來沒有使它成功,這導致我相信問題是我如何實現API get方法。任何幫助重寫該方法正確返回非常感謝!從Mongoose文檔返回JSON數據到客戶端Javascript

澄清:我想要的是能夠像訪問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

p There are {{tracks.length}} posts 

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

向您的$ http.get添加錯誤子句。我懷疑有一個錯誤:錯誤(功能(數據,狀態,標題,配置){console.log(data); }) – asgoth

回答

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 
    }); 
    }); 
}; 
} 
+0

難道這是獲得j的唯一方法 –

相關問題