5

nodejs のコレクションで異なる ID を反復処理しようとしています。次のコードのように機能するもの:

//Callbacks removed for readability

var thisPost = mongoose.model('Post').findOne({tags: 'Adventure'});
console.log(thisPost.title); // 'Post #1 - Adventure Part 1'

var nextPost = thisPost.next({tags: 'Adventure');
console.log(nextPost.title); // 'Post 354 - Adventure Part 2'

これまでの最善のアイデアは、スキーマにリンクリストを追加して、特定の ID への次の参照で find() を呼び出すことができるようにすることですが、この Mongoose 参照 (thisPost) を使用できるようにするための「トリッキー」ではないものを望んでいました。私のfind()が開始できるカーソルとして。

ありがとう

編集:反復は、複数のページクエリで機能することを意図しています。より良い例:

//Callbacks removed for readability

//User 'JohnDoe' visits the website for the first time
var thisQuote = mongoose.model('Quote').findOne().skip(Math.rand());
res.send(thisQuote); // On page output, JohnDoe will see the quote 42
//Saving the current quote cursor to user's metadatas
mongoose.model('User').update({user: 'JohnDoe'}, {$set: {lastQuote: thisQuote }});

//User 'JohnDoe' comes back to the website
var user = mongoose.model('User').findOne({user: 'JohnDoe});
var thisQuote = user.lastQuote.next();
res.send(thisQuote); // On page output, JohnDoe will see the quote 43
//Saving the current quote cursor to user's metadatas
mongoose.model('User').update({user: 'JohnDoe'}, {$set: {lastQuote: thisQuote }});

//And so on...
4

1 に答える 1

11

Mongoose のストリーミング機能を調べることができます。

var stream = mongoose.model('Post').find({tags: 'Adventure'}).stream();

// Each `data` event has a Post document attached
stream.on('data', function (post) {
  console.log(post.title);
});

返されるQueryStreamNode.js の Streamstream()を継承しているため、必要に応じてandを使用して興味深いことを行うことができます。pauseresume

[編集]

あなたの質問をもう少し理解したので、QueryStream はおそらくあなたが使いたいものではないと思います。私は今日これに少し取り組み、https://gist.github.com/3453567で実用的なソリューションを得ました。Gist ( git://gist.github.com/3453567.git) を複製して実行するだけnpm installnode index.js、 のサイトにアクセスできるはずですhttp://localhost:3000。ページを更新すると、「次の」引用が表示され、最後に到達するとラップアラウンドするはずです。

これは、いくつかの理由で機能します。

まず、ユーザーの「最後に閲覧した」引用への参照をデータに保存します。

var UserSchema = new mongoose.Schema({
  user: String,
  lastQuote: { type: mongoose.Schema.Types.ObjectId, ref: 'Quote' }
});

すると、返される UserUser.findOne().populate('lastQuote')lastQuote属性は、MongoDB に格納されているフィールドの値 (ObjectId) によって参照される実際の Quote オブジェクトになります。

next()次のコードにより、この Quote オブジェクトを呼び出すことができます。

QuoteSchema.methods.next = function(cb) {
  var model = this.model("Quote");
  model.findOne().where('_id').gt(this._id).exec(function(err, quote) {
    if (err) throw err;

    if (quote) {
      cb(null, quote);
    } else {
      // If quote is null, we've wrapped around.
      model.findOne(cb);
    }
  });
};

これは、次の引用を見つけるか、最初の引用にラップアラウンドする部分です。

コードを見て、ご不明な点がございましたらお知らせください。

于 2012-08-23T18:13:25.623 に答える