2016-01-24 41 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(); 
    } 
}); 
相關問題