猫鼬 - 转到下一个元素

red*_*red 5 mongoose mongodb node.js

我试图在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'
Run Code Online (Sandbox Code Playgroud)

到目前为止最好的想法是在我的模式中添加一个链表,这样我就可以在下一次对特定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...
Run Code Online (Sandbox Code Playgroud)

Mic*_*ley 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);
});
Run Code Online (Sandbox Code Playgroud)

QueryStreamstream()返回的东西,它继承自Node.js的Stream,所以你可以使用它来做一些有趣的事情pause,resume如果你需要的话.

[编辑]

既然我更了解你的问题,我会说QueryStream可能不是你想要使用的.我今天做了一点工作,并在https://gist.github.com/3453567获得了一个有效的解决方案; 只需克隆Gist(git://gist.github.com/3453567.git),运行npm install然后node index.js你就可以访问该网站了http://localhost:3000.刷新页面应该给你"下一个"引用,当你到达最后它应该环绕.

这有效,因为有几件事:

首先,我们节省了引用到他们的数据用户的"最后一次查看"报价:

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

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

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);
    }
  });
};
Run Code Online (Sandbox Code Playgroud)

这是找到下一个引用或者包围第一个引用的部分.

看看代码,如果您有任何问题,请告诉我.