完成后,cursor.foreach()中修改的集合将被删除

时间:2016-02-07 00:17:29

标签: mongodb meteor collections foreach

我正在尝试遍历一个集合来构建一个新集合(hits_col),其中包含来自第一个集合的条目计数。到目前为止我编写的代码似乎在迭代发生时起作用,但是,一旦.forEach()方法完成,新集合(hits_col)就会被删除。

RAW_COL.find({}, {fields: {created_time: 1}}).forEach(function (doc) {
  var date = moment.unix(doc.created_time).format("YYYYMMD");
  var hitCOUNT = hits_COL.findOne({'_id': date});

  try {
    if(tags === undefined) {
      hits_COL.insert({'_id': date, 'hits': 1}, function (err, id) {
        if(err == null) console.log("Entry " + id + " was created.");
        else console.log(err);
      });
    } else {
      hitCOUNT.hits = hitCOUNT.hits + 1;
      hits_COL.update({'_id': date}, {'hits': tags.hits});
    }

  } catch (err) {throw err;}
}

当RAW_COL正在迭代时,我可以转到我的收藏并检查当前的条目,一切都很顺利。

meteor:PRIMARY> db.hits.find()
{ "_id" : "20160121", "hits" : 7887 }
{ "_id" : "20160120", "hits" : 7417 }
{ "_id" : "20160122", "hits" : 7533 }
{ "_id" : "20160124", "hits" : 8047 }
{ "_id" : "20160123", "hits" : 8262 }
{ "_id" : "20160125", "hits" : 7579 }
{ "_id" : "20160126", "hits" : 2111 }
{ "_id" : "20160119", "hits" : 7594 }
{ "_id" : "20160118", "hits" : 7788 }
{ "_id" : "20160117", "hits" : 7746 }
{ "_id" : "20160116", "hits" : 7609 }
{ "_id" : "20160115", "hits" : 3348 }

然而,在forEach()函数完成后,集合被删除或者某个东西和同一个mongo调用都没有返回任何内容。

meteor:PRIMARY> db.hits.find()

我在这里缺少什么?

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

上面的代码是以

开头的



Meteor.startup(function () { hits_COL.remove({}); });




在forEach()调用之后调用。