【问题标题】:How to get the value of the last item in a Mongo collection如何获取Mongo集合中最后一项的值
【发布时间】:2017-01-18 18:32:41
【问题描述】:

我读了一个 Mongo 集合,我想获取最后一项的值。我做了一种从最旧到最新排序的方法(stackoverflow question),只取第一项,但我无法得到他的值。

这是我在集合中插入数据的代码:

'container.start': function(id) {
    var ctn = docker.getContainer(id);
    ctn.start(Meteor.bindEnvironment(function(err, data) {
      if(err){
        ErrorsContainer.upsert({

        }, {
            error: err
        });
        console.log(err);
      }else{
        console.log(data);
      }
    }));
}

然后是我读取集合的代码:

  'click .start'(event) {
      const idDB = this._id
      const container = InfosContainers.findOne({_id: idDB});
      const name =  container["nameContainer"];
      const idContainer = container["idContainer"];
      console.log("the container: " + name + " is going to be started. His id is: " + idContainer);
      Meteor.call("container.start",idContainer);
      //get the last error
      var error = ErrorsContainer.find({}, {sort: {_id: 1, limit: 1}});
      if(error){
        alert(error[error]); //tried error.error too
      }
  }

那么我怎样才能得到集合错误的值呢?

【问题讨论】:

  • {sort: {_id: 1, limit: 1}} 应该是 {sort: {_id: 1}, limit: 1}
  • 问题是集合的错误是包含其他对象!所以看看我的答案

标签: javascript mongodb meteor


【解决方案1】:

问题是集合的错误包含其他东西,我不得不这样做:

  var lastError = ErrorsContainer.findOne({}, {sort: {_id: 1}});
  console.log(lastError.error.message);

【讨论】:

    【解决方案2】:

    { sort: { created : -1 } }
    

    其中 created 是文档的创建时间 -1 用于按 DEC 顺序排序(1 用于按 INC 顺序排序)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-17
      • 1970-01-01
      • 1970-01-01
      • 2016-09-15
      • 2012-06-10
      • 2015-12-07
      相关资源
      最近更新 更多