2017-06-22 2 views
0

私は "general_roasts"というコレクションを持っていて、ランダムな文書を取得して返しています。ここでSkip and Limit Options Meteor/MongoDBでヌルを返す

meteor:PRIMARY> db.general_roasts.find() 
{ "_id" : ObjectId("594b389caad4dc3ae16c5f09"), "text" : "roast 11", "contributor" : "" } 
{ "_id" : ObjectId("594b38a1aad4dc3ae16c5f0a"), "text" : "roast 12", "contributor" : "" } 
{ "_id" : ObjectId("594b38a5aad4dc3ae16c5f0b"), "text" : "roast 13", "contributor" : "" } 
{ "_id" : ObjectId("594b38a7aad4dc3ae16c5f0c"), "text" : "roast 14", "contributor" : "" } 
{ "_id" : ObjectId("594b38aaaad4dc3ae16c5f0d"), "text" : "roast 15", "contributor" : "" } 

コードされる:

import { Mongo } from 'meteor/mongo'; 
import { Meteor } from 'meteor/meteor'; 

const Categories = new Mongo.Collection('categories'); 
const GeneralRoasts = new Mongo.Collection('general_roasts'); 
console.log("GENERAL ROASTS: " + GeneralRoasts.find().fetch()); 

Meteor.methods({ 
    'Roasts.random': ({category}) => { 
    console.log("received random roast request: " + category); 
    if (category == 'general') 
    { 
     let count = GeneralRoasts.find().count(); 
     let index = Math.floor(Math.random() * count); 
     console.log("count: " + count + " index: " + index); 
     //var roast = GeneralRoasts.find({skip: index}).fetch(); 
     var roast = GeneralRoasts.find({}, {skip: index, limit: 1}); 
     console.log("returning roast: " + roast.text); 
     return roast; 
    } 
    } 
}); 

Meteor.publish('general_roasts',()=> { 
    console.log("published"); 
    return GeneralRoasts.find(); 
}); 
Meteor.publish('categories',() => { 
    return Categories.find(); 
}); 

export default GeneralRoasts; 

"Roasts.random" のログイン出力である:

received random roast request: general 
I20170621-22:02:32.059(-7)? count: 5 index: 4 
I20170621-22:02:32.060(-7)? returning roast: undefined 

ここdb.general_roasts.findの出力は、()であります誰もが "ロースト14"が返されるべきときにnullが返される理由を知っていますか?

ありがとうございます!

+0

'4を作るために' skip:count-1'にしてはいけませんか? '5'をスキップすると、カーソルの最後に到達するからです。 「4」をスキップすると、最後の文書が表示されます。たぶんあなたはそれをシェルに数回打ち込んで、それを沈んでください。 –

+0

インデックスの値に基づいてスキップします。これは4です。したがって、ドキュメントの最後には到達してはいけません。 – AdeptLearner

+0

あなたは間違っています。インデックスは「n-1」であり、「n」ではありません。たとえば、「最初の」ドキュメントを取得するために「0」をスキップします。 '1'をスキップすると、それは「2番目の」ドキュメントです。それを今すぐ入手しますか? –

答えて

0

Neil Lunnの言葉通り、「ロースト15」を受け取り、「ロースト14」は受け取りません。

{スキップ:0を、制限:1} 'ロースト11'、そうである{:4、リミット:スキップ1} 'ロースト15'

ことそして、あなたはそれを取得していないので、あなたは未定義取得します。

var roast = GeneralRoasts.find({}, {skip: index, limit: 1}).fetch(); 
+0

これは本当です、キャッチのおかげで! – AdeptLearner

+0

答えを正しいとマークできますか?ありがとう。 – bordalix

0

変更

var roast = GeneralRoasts.find({}, {skip: index, limit: 1}); 

それは(すなわち見つける判明)のみカーソルを返すので、私はGeneralRoasts.find({}を使用していた、{スキップ:インデックス、リミット:1})。fetch();

これが私の問題を解決しました。

関連する問題