Express Controller Mongoose查询Ember-Data预期格式

时间:2013-11-16 14:40:54

标签: javascript node.js ember.js mongoose ember-data

我正在尝试使用后端的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控制器。什么是最佳实践或处理查询范围的方法,以便我可以将每个子注释推送到注释中,以实现Ember数据的正确有效负载格式。

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逻辑中创建闭包,但似乎无法将注释推送到外部作用域的comments数组中。我确定我错过了一些基本的东西。

1 个答案:

答案 0 :(得分:0)

答案是使用promise,.map()和mongoDB $ in子句。总之,这可以很好地清理这个实现。我在Mongoose API文档中隐藏了Promise和$ in。

exports.index = function(req, res){

  var promise = Post.find({"user_id": 162}).exec();

      promise
        .then(function(posts){

            var ids = posts.map(function (p) {
              return p._id;
            });

            Comment
              .find({
                '_creator': {
                  $in: ids
                }
              }, function(err, comments) {
                console.log(comments);

                var payload = {"posts": posts, "comments": comments}
                return res.send(200, JSON.stringify(payload));

              });

        })

}