1

我正在尝试使用 Nodejs、mongoose 和 MongoDB 进行 map reduce 操作。我有一个相当平坦的模式结构,我想获得每个“命名”对象的值/日期对列表。map reduce 函数显然有问题,但我不知道如何修复它以获得我想要的格式。

MongoDB 文档架构如下:

{ "name" : "object1", "value" : "123", "date" : "2013-01-02 01:00:00" }
{ "name" : "object1", "value" : "456", "date" : "2013-01-02 02:00:00" }
{ "name" : "object2", "value" : "123", "date" : "2013-01-02 02:00:00" }

我在 Mongoose Schema 中使用的 map reduce 函数如下:

var o = {};
o.map = function () { 
  emit(
    { 'name': this.name },
    {'data': [ { 'value': this.value, 'date': this.date} ] }
  )
}

o.reduce = function (k, vals) { 
  var reduced = {'data': []};
  for (var i in vals) {
    reduced.data.push(vals[i]);
  }
  return reduced;
}

this.mapReduce(o, function(err, model) {
  if(err) console.log(err);
  model.find().exec(cb);
});

我想看到的是一些 JSON

[
  {
    "name": "object1",
    "data": [
      {
        "value": "123",
        "date": "2013-01-02T01:00:00.123456"
      },
      {
        "value": "456",
        "date": "2013-01-02T02:00:00.123456"
      },
    ]
  },
  {
    "name": "object2",
    "data": [
      {
        "value": "123",
        "date": "2013-04-22T13:10:03.893018"
      },
      ...
    ]
  },
  ...

但我最终得到了这个嵌套的混乱!有人可以给我指点一下我错过了什么!!

[
  {
    "_id": {
      "name": "object1"
    },
    "value": {
      "data": [
        {
          "data": [
            {
              "data": [
                {
                  "data": [
                    {
                      "value": "123",
                      "date": "2013-01-02T02:00:00.123456"
                    }
                  ]
                },
                {
                  "data": [
                    {
                      "value": "465",
                      "date": "2013-01-02T01:00:00.123456"
                    }
                  ]
                },
                ... etc
4

1 回答 1

0

尝试这样的事情:(未经测试,但我认为这个想法就在这里:))

var o = {};
o.map = function () { 
  emit(this.name, { 'value': this.value, 'date': this.date} )
}

o.reduce = function (k, vals) { 
  var reduced = {name: k, data : []};
  for (var i in vals) {
    reduced.data.push(vals[i]);
  }
  return reduced;

  // or just return vals? it's already the array you want.
}
于 2013-04-22T21:17:47.197 回答