0

I know that the title might be a bit vague, but I will elaborate here.

basically what I am trying to achieve is the following:

I have a collection with documents that have the following scheme:

bookId: <uuid>
genre: <string>
isTaken: true
historyIndex: each time something happens i increment this 
returnedAt: not required but will be present on documents with historyIndex
takenAt: not required but will be present on documents with historyIndex


there are documents with no historyIndex field because they are representing the book itself without the action that were done to the book.

what i want to do is this:

I want to query the books by their unique uuid and then use the documents with historyIndex and add them to the main documents as in an array as called bookEvents

so the final results will be

bookId:
bookEvents: [] --> an array with all the entries that contain history index

basically everytime the status of the book changes, i am inserting an event with the date it was taken on and the date it was returned on

What would be the best way of achieving such thing ?

Should I query once and iterate in my code ? Should I query twice (once where the fields exist and once where they don't) ?

Thank you in advance for all the people that will try to help!

Eitank
  • 570
  • 8
  • 21

1 Answers1

0

You can use the plugin or events to achieve this.

var CounterSchema = new mongoose.Schema({
    _id: {type: String, required: true},
    seq: { type: Number, default: 0 }
});
var counter = mongoose.model('counter', CounterSchema);

var entitySchema = mongoose.Schema({
    sort: {type: String}
});

entitySchema.pre('save', function(next) {
    var doc = this;
    counter.findByIdAndUpdateAsync({_id: 'entityId'}, {$inc: { seq: 1} }, {new: true, upsert: true}).then(function(count) {
        console.log("...count: "+JSON.stringify(count));
        doc.sort = count.seq;
        next();
    })
    .catch(function(error) {
        console.error("counter error-> : "+error);
        throw error;
    });
});

refer https://stackoverflow.com/a/40137723/8201020

Aditya Joshi
  • 1,033
  • 7
  • 20