【发布时间】:2013-11-16 14:40:54
【问题描述】:
我正在尝试在后端使用 Express/Mongoose 以 Ember-Data 的预期格式格式化 json。有效载荷需要采用以下格式:
{
"posts": [{
"id": 1,
"user_id": 162,
"short_desc": "sdfdsfsf",
"comments_ids": [1, 2]
}, {
"id": 2,
"user_id": 162,
"short_desc": "xcvcxvcxv",
"comments_ids": [3, 4]
}],
"comments": [{
"id": 1,
"name": "lorem ipsum",
"body": "lorem ipsum"
}, {
"id": 2,
"name": "lorem ipsum",
"body": "lorem ipsum"
}, {
"id": 3,
"name": "lorem ipsum",
"body": "lorem ipsum"
}, {
"id": 4,
"name": "lorem ipsum",
"body": "lorem ipsum"
}]
}
Mongoose 模型是这样设置的:
var PostSchema = new Schema({
metadata : [{ type: Schema.Types.ObjectId, ref: 'Comment' }],
user_id: { type: Schema.Types.ObjectId, ref: 'User' },
createdAt : {type : Date}
})
var CommentSchema = new Schema({
_creator : { type: Schema.Types.ObjectId, ref: 'Post' },
name: {type : String},
body: {type : String}
})
这是我的基本 Express 控制器。什么是处理查询范围的最佳实践或方法,以便我可以将每个子评论推送到 cmets 以实现 Ember-data 的正确有效负载格式。
exports.index = function(req, res){
comments = [];
Post
.find({"user_id": 162},function (err, posts) {
if (err) throw err;
posts.forEach(function(post){
Comments.find({"_creator": post._id},function (err, comments) {
comments.forEach(function(comment){
console.log("forEach comment: " + comment);
comments.push(comment);
})
});
})
var payload = {"posts": posts, "comments": comments} // comments is empty
return res.send(200, JSON.stringify(payload));
})
}
我尝试在我的 forEach 逻辑中创建闭包,但似乎无法将注释推送到外部范围内的 cmets 数组中。我确定我在这里遗漏了一些基本的东西。
【问题讨论】:
-
转向 Mongoose Promise API。
标签: javascript node.js ember.js mongoose ember-data