2

Here is my schema of the collection:

var mongoose = require('mongoose');

var urlSchema = new mongoose.Schema({
  url:  String,
  easeDate: { type: Date, index: 1},
  created: { type: Date, default: Date.now }
});

I need to do an update action with the oldest document (by easeDate) to change its easeDate date to «now + some timeout» and get the affected document. Is it possible in one request?

Basically, I want to make something like a queue from the collection (the "oldest" one is the next one pulled out i.e. first in first out). Deletion of urls (documents in the collection) is done by other conditions. I don't want to delete from queue but put to the end of it by updating easeDate.

Finally, I want to take the available url and set a timeout to it, so that the next time there was returned the next url. If it was the last url, then null is returned next time, because of timeout.

And if I can update it so, how can I query the database (mongoose) to get the next url where easeDate < Date.now()? Could you please give an example in JavaScript?

Ruslan
  • 199
  • 3
  • 5

1 Answers1

2

Use findAndModify() with sort

If you're accessing your stack from a single machine you can do so using findAndRemove:

Model.collection.findAndModify({query:{}, sort:{created: 1}, remove:true})

You need to access collection because mongoose doesn't implements

findAndModify, you have findOneAndUpdate but it doesn't delete documents

More information:

Does Mongoose support the Mongodb `findAndModify` method?

Community
  • 1
  • 1
Sam Quinn
  • 3,310
  • 1
  • 16
  • 11
  • Sorting is actually supported by the [`.findOneAndRemove()`](http://mongoosejs.com/docs/api.html#model_Model.findOneAndRemove) mongoose method as well. So you don't really need to dig into the underlying driver. – Neil Lunn Jun 20 '17 at 03:26
  • I guess,`.findOneAndUpdate()` is the best in my situation (I updated the question). What about querying the next available document in the queue? – Ruslan Jun 20 '17 at 22:07