Fawn
Promise based Library for transactions in MongoDB
Fawn provides the ability to carry out edits on a mongoDB database as a series of steps. If an error occurs on any of the steps, the database is returned to its initial state (its state before the transaction started). It's based on the two phase commit system described in the MongoDB docs. Check out this Medium article for a more detailed look.
View on GitHub
Getting Started:
Start mongoDB in a terminal: mongod
Then:
npm install fawn
Usage:
var Fawn = ; Fawn;
or
var mongoose = ;mongoose; Fawn;
Examples
Say you have two bank accounts, one belongs to John Smith and the other belongs to Broke Ass. You would like to transfer $20 from John Smith to Broke Ass. Assuming all first name and last name pairs are unique, this might look like:
var task = Fawn; //assuming "Accounts" is the Accounts collectiontask ;
Files can be saved to and removed from GridFS. Here's how you might update a user's profile image:
var newImageId = someMongoDbId; task ;
By default, tasks run using the native driver but you can opt for mongoose. If you prefer not to chain function calls, you don't have to:
tasktasktask ;
The server could crash before a task is complete, You can use the Roller to rollback all incomplete transactions before starting your server:
// assuming Fawn has been initialized. See Fawn.init belowvar roller = Fawn; roller ;
API
- Fawn.init
- Fawn.Task
- task.initmodel
- task.save
- task.update
- task.options
- task.remove
- task.saveFile
- task.removeFile
- task.run
- Fawn.Roller
- Roller.roll
Fawn.init(db, _collection, options): Initialize Fawn
db (required): mongoose instance or connection string
_collection (optional): Name of collection used internally by Fawn to store transactions
options (optional. lol): Connection options. Same as mongoose connection options
Note: if you're running multiple apps connected to the same db, provide a string value for _collection that's unique to each app. Do this to avoid a situation where one app rolls back the unfinished transaction(s) of another app.
If you're using mongoose in your project initialize Fawn with mongoose:
var mongoose = ; mongoose; // remember, _collection is optionalFawn;
Without mongoose, Initialize Fawn like so:
// options object (http://mongoosejs.com/docs/connections.html#options)var options = user: "teh_huose_kat" pass: "teh_Kitti_passwrod"; var collection = "Fawn_collection_name_if_you_want_to_specify"; // remember, _collection and options are optionalFawn;
Fawn.Task(): Create a Fawn task
returns: A new task
After intitializing Fawn, create a task like so:
var task = Fawn;
task.initModel(modelName, schema): To initialize a model with a Schema.
modelName (required): Name of the collection associated with this model
schema (optional): Same as object passed to mongoose Schema. Also see validation
Note: For model validation to work, run task with useMongoose set to true
Initalizes a mongoose model with the provided schema. If you're using mongoose, define your models with mongoose wherever possible. If the model has been defined by mongoose before this function is called, mongoose will throw an OverwriteModelError and if it was defined by Fawn, Fawn will throw an Error. Models can be defined only once.
var schema = name: type: String required: true specials: title: String year: Number; task ;
Save operations to the "comedians" model will validate against the schema;
task.save(model, doc): To save a document
model (required): Name of the collection we're saving to or a mongoose model or a mongoose document
doc (optional): Object to save or a mongoose document
these are all valid:
var Cars = mongoose;var toyota = make: "Toyota" year: 2015; task;task;task;task;task;
Note: No changes will be made to to your database until you call task.run()
task.update(model, condition, data): To update a document
model (required): Name of the collection we're updating or a mongoose model or a mongoose document
data (optional): Data to update with same as in mongoose and mongodb
These are all valid
var Cars = mongoose; task;task; Cars;
Note: No changes will be made to to your database until you call task.run()
task.options(options): Add options to an update task.
options (required): Update options = mongoose options + {viaSave: Boolean}
Attach to update call as shown
task optionsmulti: true; // Also valid task;taskoptionsmulti: true;
The viaSave option allows you update a mongoose document using the save function. It's useful if you want to trigger mongoose pre save hooks. For this option to work you must run the task using mongoose
with mongoose:
var doc = someMongooseDocument; docsomeProperty = newValue; doc;
with Fawn:
var doc = someMongooseDocument; var newDoc = doc; newDocsomeProperty = newValue task optionsviaSave: true ;
Note: No changes will be made to to your database until you call task.run()
task.remove(model, condition): Remove document(s) from a collection
model (required): Name of the collection we're deleting from or a mongoose model or a mongoose document
condition (optional): Same as in mongoose
These are all valid
var Cars = mongoose; // removes all cars with year === 2015task;task; Cars;
Note: No changes will be made to to your database until you call task.run()
task.saveFile(filePath, options): Save a file to the db via GridFS
filePath (required): Path to the file
options (optional): Same as GridStore options
Saves the file at "filePath" to the database using GridFS. The result of this operation is the saved file's object. See File object
task ;
Note: No changes will be made to to your database until you call task.run()
task.removeFile(options): Remove a file from the db via GridFS
options (required): Same as GridStore options
Removes a file that matches "options" from the database using GridFS. The result of this operation is a GridStore instance (can be ignored). See GridStore
task ;
Note: No changes will be made to to your database until you call task.run()
task.run(options): Run a task.
options: {useMongoose: Boolean}
returns: Promise
For the database changes to occur, you must call task.run(). This function returns a promise. On success, the promise is resolved with an array containing the node-mongodb-native or mongoose result of each operation in sequence. If an error occurs, the promise is rejected with the error that caused the failure.
task // or run({useMongoose: true}); ;
- the result of save is, insertOneWriteOpResult for mongodb native, and the saved doc for mongoose
- the result of remove is, deleteWriteOpResult for mongodb native, and writeOpResult for mongoose
- the result of update is, updateWriteOpResult for mongodb native, and the mongodb update output for mongoose
- the result of saveFile is the saved file object
- the result of removeFile is a GridStore instance
Fawn.Roller(): Get the Roller object.
returns: The Roller object
After initializing Fawn, get the Roller like so:
var Roller = Fawn;
Roller.roll(): Roll back all incomplete transcations
In case of a server crash or any other fatal error, use the roller to return all the documents affected by incomplete transactions to their original state. Should only be used when no tasks are in progress, usually on server startup.
var roller = Fawn; roller ;
Miscellaneous
Using the result of previous steps in subsequent steps
You might want to use the result of a previous step in a subsequent step. You can do this using a template object with the key "$ojFuture". Syntax: {$ojFuture: "indexOfStep.resultProperty1.property2.-----.propertyN"}. Here's how:
task //result will be {_id: someMongoId, name: {full: "Brody Obi"}}
To use this feature you need to know the exact format of the step's result. For Reference: Results
Test
To test this module, start mongodb in a terminal
mongod
Then cd to the project directory and run
npm test