mongoose – 转到下一个元素

我正在尝试通过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' 

到目前为止最好的想法是添加一个链表到我的模式,所以我可以调用find()通过我的下一个引用特定的ID,但我希望有一些“棘手”,这将允许我使用这个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... 

你可以看看Mongoose的stream媒体function:

 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); }); 

QueryStream是stream()返回的内容,它inheritance自Node.js的Stream ,因此如果需要,可以使用pauseresume来做一些有趣的事情。

[编辑]

现在我明白了你的问题,我想说QueryStream可能不是你想要的。 我今天做了一些工作,并在https://gist.github.com/3453567获得了一个工作解决scheme; 只要克隆Gist( git://gist.github.com/3453567.git ),运行npm install ,然后运行git://gist.github.com/3453567.git ,你应该可以访问http://localhost:3000这个站点。 刷新页面应该给你“下一个”的引用,当你到达最后它应该环绕。

这是因为一些事情的作品:

首先,我们在其数据中保存对用户“上次查看”报价的引用:

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

现在,当我们做User.findOne().populate('lastQuote') ,返回的User的lastQuote属性将是一个实际的Quote对象,由MongoDB中存储的字段的值(ObjectId)引用。

由于以下代码,我们可以在这个Quote对象上调用next()

 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); } }); }; 

这是发现下一个报价的部分,或者换行到第一个报价。

看看代码,让我知道如果你有任何问题。