Skip to content

Instantly share code, notes, and snippets.

@melissamarima
Last active November 12, 2015 17:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save melissamarima/27a8924b4ab967c45853 to your computer and use it in GitHub Desktop.
Save melissamarima/27a8924b4ab967c45853 to your computer and use it in GitHub Desktop.
var mongoose = require('mongoose');
var collectionASchema = new mongoose.Schema({field1: Number, field2: Number});
var collectionBSchema = new mongoose.Schema({field1: Number, field2: Number});
collectionASchema.index({field1: 1});
collectionBSchema.index({field1: -1});
mongoose.model('collectionA', collectionASchema);
mongoose.model('collectionB', collectionBSchema);
collectionBSchema.methods.addToCollectionB = function(cb){
// `this` is the newDocB
var newDocB = this;
var collectionA = mongoose.model("collectionA");
// 1. If collection A is empty, push newDocB onto collection B, and stop
collectionA.find(function(err, collectionADocsArray){
if (err){return err;}
if (collectionADocsArray.length == 0){
newDocB.save(cb); // saves newDocB to collectionB
return; // ends addToCollectionB()
}
// 2. Get the current collection A's first element
collectionA.find({}).sort({price:1}).limit(1).exec(function (err, collectionADocsArray){
if (err) {return err;}
var docA = collectionADocsArray[0];
// faking a while in async http://stackoverflow.com/a/15902899/4825465
(function loop(){
// 3. check loop condition
if (docA.field2 > 0){
// 4. check which of the two ways to modify newDocB
if (docA.field1 > 0){
// 5. one way removes docA from collectionA
newDocB.field1 -= docA.field1;
collectionA.findByIdAndRemove(docA.id, function(err, doc){
if (err) {return err;}
// docA is removed
// I think async breaks the continuity since this point
});
} else {
// 6. the other way breaks out of the loop
newDocB.field1 = 0;
return; // I hope this return breaks out of loop
}
// 7. if collectionA is empty, break out of the loop
collectionA.find(function(err, collectionADocsArray){
if (err){return err;}
if (collectionADocsArray.length == 0){
return; // I hope this return breaks out of loop
}
});
// 8. loads the new docA and continues to the next loop
collectionA.find({}).sort({price:1}).limit(1).exec(function (err, collectionADocsArray){
if (err) {return err;}
docA = collectionADocsArray[0];
loop();
});
}
}());
// 9. Loop is done, check if newDocB needs to be saved
if (newDocB.field1 >= 0){
newDocB.save(cb); // saves newDocB to collectionB
return; // ends addToCollectionB()
}
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment