upsertAsync: function(req, res, next) {
var datas = req.body;
var user = req.body.user;
async.each(datas, function(data, cb) {
sequelize().transaction({
autocommit: true
}, function(t) {
models.Customer.upsert({
id: data.id,
code: data.code,
createdBy: user.name,
modifiedBy: user.name
}, {
transaction: t
}).then(function(customer) {
cb();
}).
catch (function(error) {
t.rollback();
res.status(500).json(error);
});
}, function(err, data) {
log.debug('error (upsertAsync)', err);
if (err) {
t.rollback();
res.status(500).json(err);
}
t.commit();
res.json({
responseCode: '200',
message: 'Customer has been created..!',
data: data
});
});
});
},
I'm using async.each to insert data into sqlite database at the same time. I want to rollback if any error occurs but it shows error which is [TypeError: Cannot set property 'options' of undefined
Related
I'm following a tutorial in the net. It's a MERN project with mongo/mongoose. When I have implemented the update function in the controller the following error has occured :
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
I've seen the answers about similar issue where they say it's because there are 2 or multiple calls of res (res.json(), res.send() etc..), but I don't see where must I change this in the following function :
module.exports.updateUser = async(req, res) => {
if (!ObjectID.isValid(req.params.id))
return res.status(400).send("ID unknown : " + req.params.id);
try {
await UserModel.findOneAndUpdate({
_id: req.params.id
}, {
$set: {
bio: req.body.bio
}
},
(err, docs) => {
if (!err)
return res.send(docs);
if (err)
return res.status(500).send({ message: err });
}
)
} catch (err) {
return res.status(500).json({ message: err });
}
};
It may be that you've mixed up two different error handling patterns.
You don't need try/catch if you're using built in error handling of findOneAndUpdate()
await UserModel.findOneAndUpdate({
_id: req.params.id
}, {
$set: {
bio: req.body.bio
}
},
(err, docs) => {
if (!err)
return res.send(docs);
if (err)
return res.status(500).send({ message: err });
}
)
and if you are using try/catch, you don't need findOneAndUpdate's error handling:
try {
const user = await UserModel.findOneAndUpdate({
_id: req.params.id
}, {
$set: {
bio: req.body.bio
}
})
return res.send(user)
} catch (err) {
return res.status(500).json({ message: err });
}
Could you please change code like this:
module.exports.updateUser = async(req, res) => {
if (!ObjectID.isValid(req.params.id))
return res.status(400).send("ID unknown : " + req.params.id);
try {
const result = await UserModel.findOneAndUpdate({
_id: req.params.id
}, {
$set: {
bio: req.body.bio
}
});
return res.send(result);
} catch (err) {
return res.status(500).json({ message: err });
}
};
Im trying to connect to an api I made with node.js but it looks like there isn't a clear way to do it if there requires a body in the request. Im able to connect to it with postman on localhost because there i can set the params in the body but when i use the heroku url it throws an error. I read that apple made it so swift can no longer make requests with a body anymore. In another project i was able to successfully connect to an api made with python but instead of passing the data to the body it was passed as params. How can I change the api/swift code to accept the data as params in swift instead of the body?
Heres the function call in swift:
func logoin() {
let params: Parameters = [
"email" : "test#email.com",
"password" : "1234"
]
AF.request("https://app_name.herokuapp.com/user/login", method: .post, parameters: params, encoding: JSONEncoding.default, headers: ["Content-Type": "application/json"]).responseJSON { response in
if let error = response.error {
print(error)
}
else{
let jsonData = try! JSON(data: response.data!)
print("json data", response)
}
}
}
Heres the api in node.js
const User = require('../models/user')
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
exports.get_user = (req, res, next) => {
const id = req.params.userId;
User.findById(id)
.exec()
.then(doc => {
console.log('From database', doc);
if (doc) {
res.status(200).json(doc);
}
else {
res.status(404).json({ message: 'No valid entry found for user ID.' });
}
})
.catch(err => {
console.log(err);
res.status(500).json({ error: err });
});
};
exports.user_login = (req, res, next) => {
User.find({ email: req.body.email }).exec().then(users => {
if (users.length < 1) {
return res.status(401).json({
message: 'Auth failed1'
});
}
bcrypt.compare(req.body.password, users[0].password, (err, result) => {
if (err) {
return res.status(401).json({
message: 'Auth failed2'
});
}
if (result) {
const token = jwt.sign({
email: users[0].email,
userId: users[0]._id
}, process.env.JWT_KEY)
return res.status(200).json({
message: 'Auth successful',
token: token
});
}
res.status(401).json({
message: 'Auth failed3'
});
});
}).catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
};
exports.delete_user = (req, res, next) => {
User.deleteOne({ _id: req.params.userId })
.exec()
.then(result => {
res.status(200).json({
message: 'User deleted'
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
};
exports.update_user = (req, res, next) => {
const id = req.params.userId;
const updateOps = {};
for (const ops of req.body) {
updateOps[ops.propName] = ops.value;
}
User.updateOne({ _id: id }, { $set: updateOps })
.exec()
.then(result => {
console.log(result);
res.status(200).json(result);
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
};
exports.signup = (req, res, next) => {
User.find({ email: req.body.email }).exec().then(user => {
if (user.length >= 1) {
return res.status(409).json({
message: 'User already exists'
});
}
else {
bcrypt.hash(req.body.password, 10, (err, hash) => {
if (err) {
return res.status(500).json({
error: err
});
}
else {
const user = new User({
firstname: req.body.firstname,
lastname: req.body.lastname,
email: req.body.email,
password: hash
});
user
.save()
.then(result => {
console.log(result)
res.status(201).json({
message: 'Successfully created user'
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
})
}
})
}
}).catch();
};
After a record is created, I'm trying to use $push to send the ID for the record that was just created into a different model.
likeRoutes.route('/add').post(function(req, res){
let like = new Like({
value: req.body.value,
_report: req.body._report
})
like.save((err, doc) => {
if (err)
res.send(err)
console.log('in router - card id', req.body._report)
console.log('doc id', doc)
Report.findOneAndUpdate({ _id: req.body._report },
{ $push: { like: doc._id } },
{ new: true , useFindAndModify: false },
(err, post) => {
if (err)
res.send(err)
res.json({doc})
}
)
})
})
When I run this, I keep getting the error of Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
I previously had it configured like this:
Report.findOneAndUpdate({ _id: req.body._report },
And it was adding the like record to the same report everytime, and did not look up by ID.
You can't call res.send and res.json one after the other.
Try this:
likeRoutes.route('/add').post(function(req, res){
let like = new Like({
value: req.body.value,
_report: req.body._report
})
like.save((err, doc) => {
if (err) return res.send(err)
console.log('in router - card id', req.body._report);
console.log('doc id', doc);
Report.findOneAndUpdate({ _id: req.body._report },
{ $push: { like: doc._id } },
{ new: true , useFindAndModify: false },
(err, post) => {
if (err) return res.send(err);
res.json({doc})
}
)
})
})
Now in case of an error you are stop execution and return the error. If no error - you are sending the result.
app.put('/edit/:id', function(req, res) {
//new actor data
var actor = {
'name': req.body.name,
'dob': req.body.dob,
'photo': req.file,
'bio' : req.body.bio
};
//updating actor
Actor.findOneAndUpdate({ _id:req.params.id }, { $set: actor }, { new: true }, function(err, data) {
if (err) {
res.send({
status: false,
error: err
});
} else {
res.send({
status: true,
data: data
});
}
});
});
I have tried it with post also and taking id through body also but still it is not working.
Tried it on postman as well as on frontend through form also. In postman also it is not able to take data or read data
Try this in order to update the actor :
Actor.findOneAndUpdate({ _id:req.params.id }, {$set: {actor:actor},}, function(err, data) {
if (err) {
res.send({
status: false,
error: err
});
} else {
res.send({
status: true,
data: data
});
}
});
I cannot remove an element inside of an array that is a property of a MongoDB Model.
Please remember this is a NodeJS module mongooseJS and not the real MongoDB so functionalities are not the same..
GOAL: Delete an object from the statusLiked array. | I have also confirmed that the value of status.id is correct.
Model:
Const userSchema = new mongoose.Schema({
myStatus: Array,
statusLiked: Array,
)};
Delete:
1. Deletes the status(works). 2. Delete the status from User.statusLiked(no work).
exports.deleteStatus = (req, res, next) => {
var CurrentPost = req.body.statusid; // sends in the status.id
Status.remove({ _id: CurrentPost }, (err) => {
if (err) { return next(err); }
// vvvv this vvv
User.update( {id: req.user.id}, { $pullAll: {_id: CurrentPost }, function(err) { console.log('error: '+err) } });
req.flash('success', { msg: 'Status deleted.' });
res.redirect('/');
});
};
What happens: The specific status(object) is deleted from the database. But the status still remains in the User.statusLiked array.
What I want to happen: Status to be deleted from the User.statusLiked array and the status to be deleted from the database. Then, reload the page and display a notification.
I got it to work somehow. Working code:
exports.deleteStatus = (req, res, next) => {
var CurrUser = req.body.userid;
var CurrentPost = req.body.post;
Status.remove({ _id: CurrentPost }, (err) => {
if (err) { return next(err); }
console.log('meeee'+CurrentPost+'user: ' +CurrUser);
req.flash('success', { msg: 'Status deleted.' });
res.redirect('/');
});
User.update(
{ _id: new ObjectId(CurrUser)},
{ $pull: { myStatus : { _id : new ObjectId(CurrentPost) } } },
{ safe: true },
function (err, obj) {
console.log(err || obj);
});
};