Sequelize.js transactions not rolling back - node.js

Hi got a question of sequelize js and transactions.
So what i am trying to do is nest inserts and commit on success, rollback otherwise here is a snippet which isn't working for me for some reason or another.
sequelize()
.transaction(function(t){
myModel
.create({
name: 'shawn;
}, {transaction: t})
.success(function(newModel) {
myModel
.create({
name: 'shawn;
}, {transaction: t})
.success(function(newModel) { t.commit()})
.error(function(err) {t.rollback()})
}
.error(function(err) {t.rollback()});
});
Don't mind any syntax error the logic which i am looking to debug. The problem occurs when i replace the commit statement on success with a rollback i dont get the 2 inserts rows rolled back?
Regards
Shawn

debug this, if error exist, you see message in console and rollback is run, else ...
sequelize()
.transaction(function(t){
myModel.create({name: 'shawn'}).success(function(newModel) {
console.log('success1')
myModel.create({name: 'shawn'})
.success(function(newModel){
console.log('success2');
t.commit();
})
.error(function(err){
console.log('error2')
t.rollback();
});
}).error(function(err) {
console.log('error1')
t.rollback()
});
});

Related

Mongoose: how to add new schema only if field does not exist?

I need help with my code.
Trying to figure what is the best way to give some errors if specific fields already exist.
Add if statement maybe on the client side if the user trying to save with a name that already exists.
Or add a statement on the server side, something I'm trying to do right now...
Here is my app.post code;
app.post('/save-file', async(req, res) => {
// Test nr3;
const saveExists = await savefile.exists({
saveFileID: req.body.saveFileID
})
if (saveExists) console.log("Save file exists")
// Note: This will log if field exist. But I need to stop somehow...
// My original code;
const SaveDB = new savefile(req.body)
try {
await SaveDB.save()
res.status(201).json({
status: 'Success',
data: {
SaveDB
}
})
} catch (error) {
res.status(500).json({
status: 'Failed',
message: error
})
}
})
Example, if my "savefiles" on my mongoDB have field --> saveFileID = "game01"
and the user writes that name, then that code should stop and give some error,
else add a new schema.

how i can get by values use function find in model by node js

I wrote code in node.js for find result from model mongoDB use mongoose
but i want get the result that include status equal waiting or accepted
This is my code that finds me results with waiting status
const Booking= require('../model/Booking')
displayBookings: async(req,res)=>{
console.log('ok get')
try {
Booking.find({owner:req.params.id, status:'waiting'}).populate('driver').exec((err,result)=>{
if(result){
res.json({result:result})
}
else
res.json({error:err})
})
} catch (err) {
res.json(err)
}
},
And this my routing code
const ControllerBooking=require('../conroller/booking')
router.get('/displayBookings/:id', ControllerBooking.displayBookings)
Booking.find({ owner: req.params.id,
status: { $in: ['waiting', 'accepted']} })
MongoDB official Documentation for $in operation

I want to check another field When I get dublicate key error for email (unique) in mongodb findoneandupdate

User.findOneAndUpdate({ _id: userFindByid }, {
$set: {
"email": req.body.email,
"username": req.body.username,
"phone_number": req.body.phone_number,
"address": req.body.address,
"isBenefactor": req.body.isBenefactor,
"location": req.body.location
}
}, { runValidators: true, context: 'query' }, (err, doc) => {
if (err) {
// if request email has already exist in db I want to check that emails isDeleted field in here . if isDeleted is true I want to update .
return res.status(500).json({ message: err.message });
}
else {
return res.status(200).json({ message: 'Your account was updated' });
}
})
//
Let me explain scenario clearly,
I registered with an email address(first#gmail.com) then I deleted my account =>(first#gmail.com)=>isDeleted=true
After that I again registered with another email address(second#gmail.com)=>isDeleted=false
Now I want to update my second email address with first one I will get an unique key error because (first#gmail.com) is in mydb ,but I have to da update process because (first#gmail.com)=>IsDelete=true
If I use { 'email': req.body.email, 'isDeleted': true} I can not update (second#gmail.com)=>isDeleted=false
I can fix the problem by using too much if statements , but I dont want to use if statements too much. I am looking for best practice for that problem.
I hope I could explain
Here is my code block , can someone help me ?
THIS ANSWER ASSUMES YOU ARE USING MONGOOSE!
One way you can do is instead of using findOneAndUpdate you can use .save this way you can issue a hook on mongoose.
For example, you would do User.save(...) then you go to your schema code and you add the following (assuming your schema name is UserSchema)
UserSchema.post('save', function(error, doc, next) {
// Error code 11000 means this is a duplicate
if (error.name === 'MongoError' && error.code === 11000) {
// So instead of throwing an error you would do anything you want
// Such as look for the other record and delete it, update its isDelete
// field, remove email, etc... really is up to you
}
next()
});
EDIT: Of course before User.save(...) you need to find the user!
For example,
User.findOne({_id:1}, function(err, doc){
// Update doc values
// Finally do doc.save(...)
})
You can make it look much better by using the async library and using async.waterfall
EDIT2: Okay so now that I understand your requirement better, here is your best solution in my opinion.
Find the user you want to update
Change email
Save
On the other side, you need to have a hook (unfortunately its poorly documented, you have to do your own digging but here is a link to mongoose documentation)
Here is how this will work
1. Hook a pre save (before actually saving execute specific block of code)
2. The block of code will only execute when the email is modified (we dont want to execute it everytime, its just a waste of resources)
3. The block of code will use deleteOne and delete the user matching that email
NOTE: For best performance make sure to index the email and make it unique!
I have created the full (similar to what you want) project with the code on here
But if you wish here are also some snippet
// This will run before saving the object
UserSchema.pre('save', function (next) {
let user = this
// Make sure to run only when email is modified
if(user.isModified('email')) {
// IF the email was modified, then attempt to delete a record with this email (if there is one, then it will be deleted otherwise it will just continue)
this.constructor.deleteOne({email:this.email, isDeleted:true}, (err) => {
err ? next(err) : next()
})
} else {
next()
}
})
// Code to save/update the user
User.findOne({_id:"1"}, function(err, user) {
if (err) {
throw err
} else {
if (user) {
user.email = "test2#test.com"
user.save(err => {
err ? console.log(err) : console.log("Success!")
})
} else {
console.log("User was not found!")
}
}
})
Good luck!

Mongoose Returned Model can't be updated

I'm pretty new to Mongoose/Mongo and node.js, so I suspect this is just a misunderstanding on my side, but...
The code sample below is the smallest failing example, not specifically my use case.
var User = app.db.model('User');
User.find({email: 'm8#test.com'}, function (err, models) {
models[0].update(function(err, mod) {
console.log(err.message)
});
});
This results in the following error: After applying the update to the document {_id: ObjectId('54647402cb955748153ea782') , ...}, the (immutable) field '_id' was found to have been altered to _id: ObjectId('546d9e0e539ed9ec102348f9')
Why is this happening? I would have thought calling update on the model returned from the initial find would have been fine.
Please note: in my use case there are things happening in between the find and the update. Specifically, I'm doing something similar to:
model.property.push(objectId)
Which I then want to commit via the update.
I'm sure this is a straight-forward issue, but I can't see anywhere in the docs I may be getting it wrong.
All help appreciated.
UPDATE:
What I actually needed to do was:
var User = app.db.model('User');
User.find({email: 'm8#test.com'}, function (err, models) {
models[0].save(function(err, mod) {
console.log(err.message)
});
});
Using 'save' rather than 'update'
I don't know if I understood
Find and Update ( for example using express )
var email = req.params.email;
User.find({email:email}, req.body, function(err,user){
if(err){
throw err;
}
//you do stuff like this
var obj = {
password:'new pass',
username:'username'
}
//use save if you want validate
User.update(user[0],obj,function(err, mod) {
console.log(err)
});
});
Only Update: ( for example using express )
User.update({email:email}, req.body, {}, function(err,user){
if(err){
throw err;
}
res.send(200, {
message : 'User updated ' + user
});
});
Remember that:
A model is a compiled version of the schema.
I hope this can help you

Node.js + mongoose [RangeError: Maximum call stack size exceeded]

I am new to Node.js and I'm facing an error :
RangeError: Maximum call stack size exceeded
I'm not able able to solve the problem because most of the stack problems in others stackoverflow questions about Node.js deals with hundreds of callback but I have only 3 here.
First a fetch (findById) then an update an later a save operation!
My code is :
app.post('/poker/tables/:id/join', function(req, res) {
var id = req.params.id;
models.Table.findById(id, function(err, table) {
if (err) {
console.log(err);
res.send({
message: 'error'
});
return;
}
if (table.players.length >= table.maxPlayers) {
res.send({
message: "error: Can't join ! the Table is full"
});
return;
}
console.log('Table isnt Full');
var BuyIn = table.minBuyIn;
if (req.user.money < table.maxPlayers) {
res.send({
message: "error: Can't join ! Tou have not enough money"
});
return;
}
console.log('User has enought money');
models.User.update({
_id: req.user._id
}, {
$inc: {
money: -BuyIn
}
}, function(err, numAffected) {
if (err) {
console.log(err);
res.send({
message: 'error: Cant update your account'
});
return;
}
console.log('User money updated');
table.players.push({
userId: req.user._id,
username: req.user.username,
chips: BuyIn,
cards: {}
});
table.save(function(err) {
if (err) {
console.log(err);
res.send({
message: 'error'
});
return;
}
console.log('Table Successfully saved with new player!');
res.send({
message: 'success',
table: table
});
});
});
});
});
The error occurs during the save operation at the end!
I use MongoDb with mongoose so Table and User are my database collections.
This is from my first project with Node.js,Express.js and MongoDB so I probably have made huge mistakes in the async code :(
EDIT: I tried to replace the save with an update:
models.Table.update({
_id: table._id
}, {
'$push': {
players: {
userId: req.user._id,
username: req.user.username,
chips: BuyIn,
cards: {}
}
}
}, function(err, numAffected) {
if (err) {
console.log(err);
res.send({
message: 'error'
});
return;
}
console.log('Table Successfully saved with new player!');
res.send({
message: 'success',
table: table
});
});
But it doesn't help the error is still coming and I don't know how to debug it :/
I've been passing for this problem too.
Basically, when you have a property with a ref, and you want to use it in a find, for example, you can't pass the whole document.
For example:
Model.find().where( "property", OtherModelInstance );
this will trigger that error.
However, you have 2 ways to fix this for now:
Model.find().where( "property", OtherModelInstance._id );
// or
Model.find().where( "property", OtherModelInstance.toObject() );
This may stop your problems for now.
There is a issue in their GitHub repo where I reported this, however it's without fix for now. See the issue here.
I kept getting this error and finally figured it out. It's very hard to debug since no real information is presented in the error.
Turns out I was trying to save an object into a field. Saving only a specific property of the object, or JSON stringifying it, worked like a charm.
Seems like it would be nice if the driver gave a more specific error, but oh well.
MyModel.collection.insert causes:
[RangeError: Maximum call stack size exceeded]
When you pass array of instances of MyModel instead of just array with values of that objects.
RangeError:
let myArray = [];
myArray.push( new MyModel({ prop1: true, prop2: false }) );
MyModel.collection.insert(myArray, callback);
No error:
let myArray = [];
myArray.push( { prop1: true, prop2: false } );
MyModel.collection.insert(myArray, callback);
There are a few ways to debug nodejs applications
Built-in Debugger
The Node.js debugger is documented here: http://nodejs.org/api/debugger.html
To place breakpoints, simply put debugger; at the place you want to break. As you said the table.save callback is giving you troubles, you could put a breakpoint inside that function.
Then you run node with the debugger enabled:
node debug myscript.js
And you will get more helpful output.
Investigating the stack
You can also use console.trace to print a stacktrace, if you have a good idea of when/where you run into problems, and want to figure out how you got there.
Good luck, I hope this helps!

Resources