Mongoose - Go to the next item

I am trying to iterate over different identifiers over a collection in nodejs. Something that would look like this:

//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'

It would be best to add a linked list to my schema so that I can call find () on my next link to a specific identifier, but I was hoping for something less "complicated" that would allow me to use this Mongoose (thisPost) link as cursor where my find () can start with.

thank

EDIT: Iteration is designed to work on multiple query pages. Best example:

//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 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 metadatas
mongoose.model('User').update({user: 'JohnDoe'}, {$set: {lastQuote: thisQuote }});

//And so on...
+5
source share
1 answer

You can see Mongoose streaming capabilities:

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(), 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' }
});

, User.findOne().populate('lastQuote'), lastQuote , , 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);
    }
  });
};

, .

, - .

+11

All Articles