【问题标题】:Express Controller Mongoose Query for Ember-Data expected format用于 Ember-Data 预期格式的 Express Controller Mongoose 查询
【发布时间】: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


【解决方案1】:

答案是使用 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));

              });

        })

}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2016-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-22
  • 2013-10-17
相关资源
最近更新 更多