exports.updateUsuarioByEmail = function (req, res) {
console.log('updateUsuarioByEmail');
console.log("PARAM ID" + req.params.email);
return Usuario.find({ email: req.params.email }, function(err, usuario) {
if(!usuario) {
res.statusCode = 404;
return res.send({ error: 'Not found' });
}
if (req.body.email != null) usuario.email = req.body.email;
if (req.body.password != null) usuario.password = req.body.password;
if (req.body.listaCardsSorting != null) usuario.listaCardsSorting = req.body.listaCardsSorting;
return usuario.save(function(err) {
if(!err) {
console.log('Updated usuario');
return res.send({ status: 'OK', usuario:usuario });
} else {
if(err.name == 'ValidationError') {
res.statusCode = 400;
res.send({ error: 'Validation error' });
} else {
res.statusCode = 500;
res.send({ error: 'Server error' });
}
console.log('Internal error(%d): %s',res.statusCode,err.message);
}
res.send(usuario);
});
});
};
The error after to execute is :
I believe that the error is the line "return usuario.save(function(err)..."
find return an Array (list of documents) . you can't do save on an array object. Instead try findOne if your email field is unique.
findOne returns a single document, so you can save that.
Replace
Usuario.find({ email: req.params.email }, function(err, usuario)
with :
Usuario.findOne({ email: req.params.email }, function(err, usuario)
To update a model it's much easier to use the findOneAndUpdate() update API. The method finds a matching document, updates it according to the update arg, passing any options, and returns the found document (if any) to the callback. The query executes immediately if callback is passed.
The syntax is:
Model#findOneAndUpdate([conditions], [doc], [options], [callback])
Parameters:
[conditions] <Object> - the query to match
[doc] <Object> - the document to update
[options] <Object> - update options
[callback] <Function> - callback
For example, the above function can be re-written to use the findOneAndUpdate() method as:
exports.updateUsuarioByEmail = function (req, res) {
console.log('updateUsuarioByEmail');
console.log("PARAM ID" + req.params.email);
var doc = {},
conditions = { "email": req.params.email },
options = { "new": true };
if (req.body.email != null) doc.email = req.body.email;
if (req.body.password != null) doc.password = req.body.password;
if (req.body.listaCardsSorting != null)
doc.listaCardsSorting = req.body.listaCardsSorting;
Usuario.findOneAndUpdate(
conditions,
doc,
options,
function(err, usuario) {
if(!err) {
console.log('Updated usuario');
return res.send({
status: 'OK',
usuario: usuario
});
} else {
if(err.name == 'ValidationError') {
res.statusCode = 400;
res.send({ error: 'Validation error' });
} else {
res.statusCode = 500;
res.send({ error: 'Server error' });
}
console.log('Internal error(%d): %s',res.statusCode,err.message);
}
}
)
};
Here remained the solution:
exports.updateUsuarioByEmail = function (req, res) {
console.log('updateUsuarioByEmail');
return Usuario.findOne({email: req.params.email}, function (err, usuario) {
usuario.email = req.body.email || usuario.email;
usuario.password = req.body.password || usuario.password;
usuario.listaCardsSorting = req.body.listaCardsSorting || usuario.listaCardsSorting;
return usuario.save(function (err) {
if (!err) {
console.log('Updated');
return res.send({status: 'OK', usuario: usuario});
} else {
if (err.name == 'ValidationError') {
res.statusCode = 400;
res.send({error: 'Validation error'});
} else {
res.statusCode = 500;
res.send({error: 'Server error'});
}
console.log('Internal error(%d): %s', res.statusCode, err.message);
}
res.send(usuario);
});
});
};
Related
I have a function to generate an available username, but always return undefined. I tried in many ways, in this case is a recursive function, but I'm always getting the same result, can you help me? Thanks
This is the code:
function generateNewUsernameAvailable(userName, number){
console.log('FUNCTION generateNewUsernameAvailable '+userName+' with number '+number);
User.countDocuments({ 'userName' : userName+number }, (err, count) => {
if (err) {
return `Error: ${err}`;
}
if (count == 0) {
return userName+number;
}else{
generateNewUsernameAvailable(userName, number+1);
}});
}
module.exports.existsUserName = function(req,res){
let userName = req.body.userName;
console.log('POST existsUserName '+userName);
User.countDocuments({ 'userName' : userName }, (err, count) => {
if (err) {
return res.status(500).send({message: `Error: ${err}`});
}
// Available
if (count == 0){
return res.status(200).send();
} else {
// Generate and return a new username available
console.log(generateNewUsernameAvailable('ricardo', 1));
res.status(400).send({message: 'newUsernameAvailable (Example ricardo1)'});
}
})
}
FindOne is faster than countDocuments/estimatedDocumentCount in this case. Both are promises, I'm going to add a possible solution:
function generateNewUsernameAvailable(userName, number){
return User
.findOne({ 'userName' : userName+number })
.then(function(result){
if (result){
return generateNewUsernameAvailable(userName, number+1);
}else{
return userName+number;
}
})
.catch(function(err) {
console.log(`Error: ${err}`);
throw err;
});
}
module.exports.existsUserName = function(req,res){
let userName = req.body.userName;
console.log('POST existsUserName '+userName);
User.countDocuments({ 'userName' : userName }, (err, count) => {
if (err) {
return res.status(500).send({message: `Error: ${err}`});
}
if (count == 0){
return res.status(200).send();
} else {
generateNewUsernameAvailable(userName,1)
.then(function(results){
return res.status(400).send({message: results});
})
.catch(function(err){
return res.status(500).send({message: `Error: ${err}`});
});
}
})
}
How can i used db.findAndUpdate table user and change my balance from previous amount to newer?
i have try to get balance and the result it show nothing, now i'm confuse to write in findAndUpdate. here's my code:
api:
app.post('/api/account/transfer', (req, res, next) => {
const { body } = req;
const {
sender,
receiver,
amount,
user,
balance,
} = body;
if (!sender) {
return res.send({
success: false,
message: 'Error: Sender cannot be blank!'
});
}
if (!receiver) {
return res.send({
success: false,
message: 'Error: Receiver cannot be blank!'
});
}
if (!amount) {
return res.send({
success: false,
message: 'Error: Fill Amount!'
});
} else if(balance < amount || balance == 0) {
return res.send({
success: false,
message: 'Insufficient funds!'
});
}
//save the new transaction
const newTransaction = new Transaction();
newTransaction.sender = sender;
newTransaction.receiver = receiver;
newTransaction.amount = amount;
newTransaction.save( (err, transaction) => {
if(err) {
return res.send({
success: false,
message: 'Error: Server error.'
});
}else{
return res.send({
success: true,
message: 'Transfer Success!'
});
}
});
//update user balance
User.findOneAndUpdate({
});
and here's the screenshoot:
so what i want is, if i'm as a receiver my balance will be increase.
Try this, the findOneAndUpdate operation does not wait for save operation to complete.
app.post('/api/account/transfer', (req, res, next) => {
const {
body
} = req;
const fields = ['sender', 'receiver', 'amount', 'balance'];
fields.forEach((field) => {
if (!body[field]) {
return res.send({
success: false,
message: 'Error: ' + field + ' cannot be blank!'
});
}
})
if (body.balance < body.amount || body.balance == 0) {
return res.send({
success: false,
message: 'Insufficient funds!'
});
}
//save the new transaction
let newTransaction = new Transaction();
// newTransaction = Object.assign(newTransaction, body); // If you want to copy all params from body to newTransaction
newTransaction.sender = body.sender;
newTransaction.receiver = body.receiver;
newTransaction.amount = body.amount;
newTransaction.save((err, transaction) => {
if (err) {
return res.send({
success: false,
message: 'Error: Server error.'
});
} else {
//update user balance
User.findOneAndUpdate({
/*query*/
}, {
/*body*/
}, (err, data) => {
if (err)
return res.send({
success: false,
message: 'Error: Server error.'
});
return res.send({
success: true,
message: 'Transfer Success!'
});
});
}
});
});
I'm trying to save the userName of a user in express session. It saves the variable in session but it returns undefined on next request to the route. However, the problem is with POST route only.
With GET request, I can save session variable and it doesn't get destroyed on further requests. I think I must be doing something wrong. I tried save() method for POST but still it saves only first time and next time it is vanished.
Here's the code:
app.use(session({
secret: 'some secret',
resave: true,
saveUninitialized: true,
cookie: {
maxAge: 36000000,
httpOnly: false
},
}));
FOLLOWING GET ROUTE WORKS.
app.get("/test", function(req, res, next){
if(!req.session.name){
req.session.name = "vikas kumar";
} else {
console.log(req.session.name);
}
res.end();
});
app.use(function (req, res, next) {
var userName = req.session.userName;
// console.log(req.session.userName);
if(userName && userName != 'undefined'){
res.send({status: "success", value: userName});
} else {
if(req.path == '/checkIfLoggedIn'){
res.send({status: "error", message: "Session ended."});
} else {
next('route');
}
}
});
FOLLOWING ROUTE SAVES SESSION ONLY ONCE.
app.post('/getProfile', function (req, res, next) {
console.log("Session", req.session.userName, req.session.name);
if(typeof req.session.userName != 'undefined'){
var userName = req.session.userName;
} else {
var userName = req.body.userName;
}
connectionPool.getConnection(function (err, connection) {
if (err) {
res.send({status: "error", message: err});
} else {
connection.query("SELECT * FROM cs_chat.users WHERE username=?", [userName], function (err, rows, fields) {
if(rows.length==1){
// console.log(">>>", req.session.userName);
req.session.userName = userName;
req.session.save();
// console.log("<<<", req.session.userName);
next();
}else{
res.send({status: "error", message: "Sorry, you're not registered."});
}
connection.release();
});
}
});
}, function (req, res) {
connectionPool.getConnection(function (err, connection) {
if (err) {
res.send({status: "error", message: err});
} else {
req.session.username = req.body.userName;
req.session.save();
connection.query("SELECT usr.username, usr.name, tsn.sender, CASE WHEN tsn.unseen is not null THEN tsn.unseen ELSE 0 END as unseen, tsn.receiver FROM users usr LEFT JOIN (SELECT sender, receiver, SUM(CASE WHEN seen = 0 THEN 1 ELSE 0 END) AS unseen FROM messages WHERE receiver = ? GROUP BY sender , receiver) tsn ON usr.username = tsn.sender where usr.username!=?", [req.body.userName, req.body.userName], function (err, rows, fields) {
if(rows.length>0){
res.send({status: "success", values: rows});
}else{
res.send({status: "success", values: []});
}
connection.release();
});
}
});
});
Am I doing something wrong?
Since it is Javascript you should be checking quality with === instead of == and for better response time releasing the connection and then again connecting to it, is simply unnecessary, when you have the connection to connectionPool just query from it twice and then release the connection.
Here is the sample modified app.post().. request, this should work:
app.post('/getProfile', function (req, res, next) {
console.log("Session", req.session.userName, req.session.name);
var userName = (req.session.userName !== undefined) ? req.session.userName : req.body.userName;
connectionPool.getConnection(function (err, connection) {
if (err) {
res.send({ status: "error", message: err });
} else {
connection.query("SELECT * FROM cs_chat.users WHERE username=?", [userName], function (err, rows, fields) {
if (rows.length === 1) {
req.session.userName = userName;
req.session.save();
} else {
res.send({ status: "error", message: "Sorry, you're not registered." });
}
});
connection.query("SELECT usr.username, usr.name, tsn.sender, CASE WHEN tsn.unseen is not null THEN tsn.unseen ELSE 0 END as unseen, tsn.receiver FROM users usr LEFT JOIN (SELECT sender, receiver, SUM(CASE WHEN seen = 0 THEN 1 ELSE 0 END) AS unseen FROM messages WHERE receiver = ? GROUP BY sender , receiver) tsn ON usr.username = tsn.sender where usr.username!=?",
[req.body.userName, req.body.userName],
function (err, rows, fields) {
if (rows.length > 0) {
res.send({ status: "success", values: rows });
} else {
res.send({ status: "success", values: [] });
}
});
connection.release();
}
});
});
at the moment i have this:
router.get('/contatos',function(req,res){
if(req.query.nome){
Contato.find({ nome: req.query.nome }, function (err, contato) {
console.log(contato);
if (JSON.stringify(contato) == "[]") {
return res.status(404).json({ Error: "that contact doesn't exist" });
}
if (err) {
return res.status(500);
}
return res.send(contato);
});
}
if(req.query.email){
Contato.find({ email: req.query.email }, function (err, contato) {
if (!contato) {
return res.status(404).json({ Error: "that contact doesn't exist" });
}
if (err) {
return res.status(500);
}
return res.send(contato);
});
}
if(Object.keys(req.query).length === 0){
Contato.find(function (err, contatos) {
if (JSON.stringify(contatos) == "{}") {
return res.status(404).json({ Error: "there are no contacts" });
}
if (err) {
return res.status(500);
}
return res.send(contatos);
}).populate('emergencia');
}
if(!req.query.nome && !req.query.email){
return res.status(400);
}
});
as you guys can see, the mongo query is almost the same the only thing that changes are the values that i pass, so to change this i tried to do a function like this:
function filtro(campo,valor,req,res){
if(arguments[0] != "undefined" && arguments[1] != "undefined"){
// i pass no parameters to filtro so here i just get all values
}
else{
Contato.find({campo:valor},function(err,contatos){
if(err){
return res.status(500);
}
return res.send(contatos);
});
}
}
then above in the first code i placed i just replace the mongo data with the return filtro("email",req.query.email)
AND
return filtro("nome",req.query.nome)
i want to know if what i am doing is correct, i just miss something because on postman it doesn't give me any response it keeps loading
To simplify it a little, you could do something like....
router.get('contatos', function(req, res){
var query = {};
if(req.query.nome) query.nome = req.query.nome;
if(req.query.email) query.email = req.query.email;
Contato.find(query, function (err, contato) {
if(err) return res.json({status : 500, error : err});
if(!contato) return res.json({status : 404, error : "Contact not found"});
return res.json(contato);
});
}
I am trying to update the value of my model and it does not work.
The weird thing is that I am printing out the result and it looks different than what I see in my database by using Robomongo.
Any thoughts why this happens?
Here is my code:
exports.create = function(req, res) {
var productId = req.query.product;
if (productId) {
Request.createWizard(req.user, { productId: productId }, function(err, request) {
Product.findById(productId, function(err, product) {
if (err) {
return console.log('oh no! error', err);
} else {
if (product.price =! 0 )
request.status = 'ready';
console.log(request);
(Here I see in the terminal: status = ready)
}
});
req.flash('success', { msg: 'Your request has been successfully created.' });
res.redirect('/discover');
});
} else {
var pages = require('../../schemas/wizard/request')();
res.render('requests/form', {
title: 'Make a Request',
pages: pages,
saveState: false
});
}
};
When I am checking the database status is still on pending.
You're changing the status property, but you're not saving the document back to the database after doing so:
Request.createWizard(req.user, { productId: productId }, function(err, request) {
Product.findById(productId, function(err, product) {
if (err) {
return console.log('oh no! error', err);
} else {
if (product.price !== 0) {
request.status = 'ready';
request.save(function(err) { // <-- save it back to the database
if (err) {
console.log('oh no! error', err);
} else {
console.log(request);
}
});
}
}
});
req.flash('success', { msg: 'Your request has been successfully created.' });
res.redirect('/discover');
});