我正在处理包含嵌套数据的文档。我已经弄清楚如何存储嵌套数据(例如,与帖子相关的评论),但我无法弄清楚如何在查询中访问该数据。这就是我所拥有的:
Node.js的
app.get('post/:post_id/comments', function(req, res) {
var Post = require('./models/post');
Post.find(
{_id: req.params.post_id},
null,
{},
function (err, data) {
if (err) return console.error(err);
return res.json(data);
}
);
});
猫鼬:
var mongoose = require('mongoose');
var postSchema = mongoose.Schema({
name : String,
post : String,
comments : [{
name : String,
text : String
}]
});
module.exports = mongoose.model('Posts', postSchema);
AngularJS:
$scope.getPostComments = function(postID){
$http({
url: 'post/'+postID+'/comments',
method: "GET"
})
.success(function (data, status, headers, config) {
$scope.comments = data.comments;
console.log(data.comments); // shows "undefined" in the console
})
.error(function (data, status, headers, config) {
$scope.status = status;
});
};
HTML:
<div ng-repeat="comment in comments">
{{comment.name}}<br>
{{comment.text}}
</div>
问题似乎出现在$scope.comments = data.comments;
中,但我可以弄清楚如何修复它,以便ng-repeat
显示我的评论(而不仅仅是空白)。有什么想法吗?
答案 0 :(得分:0)
正确的解决方案是在返回的数据上使用以下内容:
$scope.comments = data[0].comments;