Last active
October 25, 2018 04:01
-
-
Save voratham/6a8de74f72a9d0cfbb10067f2afb31bb to your computer and use it in GitHub Desktop.
mongoose-transaction
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // ESM syntax is supported. | |
| import mongoose from "mongoose"; | |
| import { MongoMemoryReplSet , MongoMemoryServer } from "mongodb-memory-server"; | |
| const replSet = new MongoMemoryReplSet(); | |
| const mongod = new MongoMemoryServer(); | |
| var dbService = null | |
| const startMongo = async () => { | |
| console.log('start mongodb') | |
| const uri = await mongod.getConnectionString(); | |
| const port = await mongod.getPort(); | |
| const dbPath = await mongod.getDbPath(); | |
| const dbName = await mongod.getDbName(); | |
| await replSet.waitUntilRunning(); | |
| dbService = mongoose .connect( uri , { useNewUrlParser: true}) | |
| .then(console.log("connection mongoo")); | |
| }; | |
| startMongo(); | |
| var User = mongoose.model("User", new mongoose.Schema({ name: String , status : { type : String , enum : ['OK' , 'PENDING'] } })); | |
| User.create({ name : "voratham" , status : 'OK' }).then( res => { | |
| // console.log('insert success :: ' , res) | |
| User.find().then( user => console.log('user :: ' , user)) | |
| }) | |
| const createUser = async () => { | |
| const session = await User.startSession(); | |
| await session.startTransaction(); | |
| try { | |
| const options = { session }; | |
| const userTarget = await User.create({ name: "Thanaphon" , status: 'FAIL' }); | |
| if(userTarget == null){ | |
| throw new Error("not fond name on user collection !") | |
| } | |
| console.log("userTarget :: ", userTarget); | |
| const updateUser = await User.create( | |
| { name: "dream" }, | |
| options | |
| ); | |
| console.log("updateUser", updateUser); | |
| await session.commitTransaction(); | |
| User.find().then( user => console.log('after commitTransaction :: ' , user)) | |
| } catch (error) { | |
| console.log("error :: ", error && error.errmsg && error.errmsg || error); | |
| await session.abortTransaction(); | |
| User.find().then( user => console.log('after abortTransaction :: ' , user)) | |
| console.log('abortTransaction....') | |
| session.endSession(); | |
| } | |
| }; | |
| createUser(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment