2016-01-24 37 views
2

这是我第一次使用Parse,至今我很喜欢它,读写数据正在工作。如何通过限制和降序获取物品索引createAt

我现在想做一些看起来很简单的事情,但在Parse的背景下看起来像是一种痛苦,我的谷歌正在失败我。

当我发现的项目是这样的:

var query = new Parse.Query(CommentClass); 
query.limit(2); 
query.descending('createdAt'); 
query.find({ 
    success: function(object) { 
     callback({ 
      comments: object 
     }); 
    }, 
    error: function(object, error) { 
     console.log('there was an error'); 
    } 
}); 

我想知道是什么返回项目的索引都在总榜单。如果我的列表中有5个项目,这将返回创建的最后2个项目,但没有办法 - 没有另一个请求知道列表中的项目数量。

+0

好吧,我会添加一些片段,但我应该去哪里尝试和解决这个问题?该文件提出了一种方法,但没有进一步解释。 – jolyonruss

+0

该指数应该是什么?不只是结果中的项目顺序? – Wain

+0

它是“列表中的索引”还是“该类中的创建索引”? – Ilya

回答

1

在Parse中没有简单的方法。一种方法是将全局索引保存在单独的对象中。在每一个新的评论中,你需要得到这个全局索引,增加它,并把它放到评论中。但是如果发表评论删除,它可能会变得混乱。下面是一个例子假定没有评论删除:

SequenceForComment.js

// A class called SequenceForComment. Only one row. 
// Only one integer property called 'sequence'. 
// You can create the row by using the Parse dashboard in the beginning. 

var SequenceForComment = Parse.Object.extend("SequenceForComment"); 

function getSequenceForComment(callback) { 
    var query = new Parse.Query(SequenceForComment); 
    return query.first().then(function (object) { 
    // https://parse.com/docs/js/api/classes/Parse.Object.html#methods_increment 
    //Increment is atomic. 
    object.increment('sequence'); 
    return object.save(); 
    }).then(function (object) { 
    callback(object.get('sequence')); 
    }, function (error) { 
    console.log(error); 
    callback(undefined); 
    }); 
} 

module.exports = { 
    getSequenceForComment: getSequenceForComment 
}; 

main.js

var SequenceModule = require("cloud/SequenceForComment.js"); 

Parse.Cloud.beforeSave("Comment", function(request, response) { 
    var comment = request.object; 

    // First time this comment will be saved. 
    // https://parse.com/docs/js/api/classes/Parse.Object.html#methods_isNew 
    if (comment.isNew()) { 

    // Get a sequence/index for the new comment 
    SequenceModule.getSequenceForComment(function(sequence) { 
     if (sequence) { 
     comment.set("sequence", sequence); 
     response.success(); 
     } else { 
     response.error('Could not get a sequence.'); 
     } 
    }); 
    } else { // Not a new save, already has an index 
    response.success(); 
    } 
}); 
相关问题