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');
});
Related
I want that my POST request sends a HTTP 409 in a certain case, so this is the code:
res.status(409).send();
However, when I tun the request in Postman it shows the result 200 OK. I put some logs in the code and I'm sure that the above line is hit.
What is wrong?
UPDATE:
Here is the full method:
app.post('/orders/:order_id/sync_status', (req, res) => {
order.findOne({ order_id: req.params.order_id},
function(err, results) {
if (err) {
res.send(`error: ${error}`);
} else if (!results) {
res.send(`no order with order_id: ${req.params.order_id}`);
} else {
status.findOne({ order_id: req.params.order_id},
function(err, result) {
if (err) {
res.send(`error: ${error}`);
} else if (result) {
res.status(409).send();
} else {
const newStatus = new status (req.body);
newStatus.save();
}
});
}
res.end();
});
});
and the Postman request:
The simple reason is because you have res.end()
The longer answer is because res.end() is executed before this piece
status.findOne({order_id: req.params.order_id}, function(err, result) {
if (err) {
res.send(`error: ${error}`);
} else if (result) {
res.status(409).send();
} else {
const newStatus = new status(req.body);
newStatus.save();
}
});
got executed due to asynchronous call/callback.
Without testing, your final code should look like this
app.post('/orders/:order_id/sync_status', (req, res) => {
order.findOne({order_id: req.params.order_id}, function(err, results) {
if (err) {
return res.send(`error: ${error}`);
}
if (!results) {
return res.send(`no order with order_id: ${req.params.order_id}`);
}
status.findOne({order_id: req.params.order_id}, function(err, result) {
if (err) {
return res.send(`error: ${error}`);
}
if (result) {
return res.status(409).send();
}
const newStatus = new status(req.body);
newStatus.save();
return res.end();
});
});
});
I am new in nodejs. I am creating a basic API to get record by id. Everything is working fine. It is returning user data from database. But when i use password variable from response in same function it give me empty value whereas i am getting value in response. I think this is async issue but i dont know how to fix it.
This is API code
var express = require('express');
var db = require('../db/database');
var bcrypt = require('bcrypt');
const router = express.Router();
router.get("/:userId", (req, res, next) => {
let uid = req.params.userId;
db.query(`SELECT * FROM users WHERE u_id = ${uid}`, (err, data)=> {
if(!err) {
if(data && data.length > 0) {
var message = '';
if(data.u_password){
//var pass = data.u_password;
if(bcrypt.compare('123456', data.u_password)) {
// Passwords match
message = 'Passwords match';
} else {
// Passwords don't match
message = 'Passwords dont match';
}
}
res.status(200).json({
message:message,
});
} else {
res.status(200).json({
message:"User Not found."
});
}
}
});
});
database.js
var mysql = require('mysql');
const pool = mysql.createPool({
connectionLimit : 10,
host: 'localhost',
user: 'root',
password: '',
database: 'lost_and_found',
debug : false
});
function executeQuery(sql, callback) {
pool.getConnection((err,connection) => {
if(err) {
return callback(err, null);
} else {
if(connection) {
connection.query(sql, function (error, results, fields) {
connection.release();
if (error) {
return callback(error, null);
}
return callback(null, results);
});
}
}
});
}
function query(sql, callback) {
executeQuery(sql,function(err, data) {
if(err) {
return callback(err);
}
callback(null, data);
});
}
module.exports = {
query: query
}
Response
{"message":""}
Please change the bcrypt.compare code to following code. It is a callback function:
bcrypt.compare('123456', data.u_password, function(err, result) {
if (err) {
// Passwords don't match
message = 'Passwords dont match';
} else {
// Passwords match
message = 'Passwords match';
}
res.status(200).json({
message:message,
});
})
EDIT 1: Please update the method to following logic:
db.query(`SELECT * FROM users WHERE u_id = ${uid}`, (err, data) => {
if (err) {
throw err;
}
if (data && data.length > 0) {
var message = '';
if (data.u_password) {
bcrypt.compare('123456', data.u_password, function (err, result) {
if (err) {
// Passwords don't match
message = 'Passwords dont match';
} else {
// Passwords match
message = 'Passwords match';
}
res.status(200).json({
message: message,
});
})
}
res.status(200).json({
message: "User Not found."
});
}
res.status(200).json({
message: "User Not found."
});
});
In my application, I have an Model say it is Record, and a Record may have several Attachment which can be uploaded to the server.
Generally, when creating a Record with Attachment(files), I will upload and save the files first, then save the record, like this:
function createOrUpdateInfo(req, res, next) {
var record = req.body;
var attachmentIds = (record.files || []).map(function (a) {
return a.id;
});
var attachmentFilter = {
where: {
id: {
$in: attachmentIds || []
}
}
};
DB.sequelize.transaction(function (t) {
var pro;
if (record.id) {
//update
//update the basic information first
return Record.update(record, {
where: {
id: req.params.id
}, transaction: t
}).then(function (num, infos) {
//find the record just saved.
return Record.findById(req.params.id).then(function (record) {
//find the attachmens which have been saved
return Attachment.findAll(attachmentFilter).then(function (atts) {
//update the record, create the association.
return record.setFiles(atts, {transaction: t});
});
})
});
} else {
//save
return Record.create(record, {transaction: t}).then(function (record) {
return Attachment.findAll(attachmentFilter).then(function (atts) {
return record.setFiles(atts, {transaction: t});
});
});
}
}).then(function (result) {
Util.sendJson(res, result)
}).catch(function (err) {
next({message: err.message, code: 500});
});
}
As shown, there are too many nested callbacks when create or update a Record.
Is this can be fixed?
I've reorganized your code a bit. Hope it helps.
function createOrUpdateInfo(req, res, next) {
var record = req.body;
var attachmentIds = (record.files || []).map(function (a) {
return a.id;
});
var attachmentFilter = {
where: {
id: {
$in: attachmentIds || []
}
}
};
DB.sequelize.transaction(function (t) {
var pro;
return (function () {
if (record.id) {
//update
//update the basic information first
return Record.update(record, {
where: {
id: req.params.id
}, transaction: t
}).then(function (num, infos) {
//find the record just saved.
return Record.findById(req.params.id);
});
} else {
//save
return Record.create(record, {transaction: t});
}
}()).then(function () {
//find the attachmens which have been saved
return Attachment.findAll(attachmentFilter);
}).then(function (atts) {
//update the record, create the association.
return record.setFiles(atts, {transaction: t});
});
}).then(function (result) {
Util.sendJson(res, result)
}).catch(function (err) {
next({message: err.message, code: 500});
});
}
I wrote this service and when I call it, the JSON response is the group is updated but when I check the group details it is not updated, the old details are still present. I don't know where or what is the issue.
This is my code:
app.post('/api/updateGroup/:group_id', function(req, res) {
var checkGroup = Group.findOne({'_id': req.params.group_id }).exec();
checkGroup.addBack(function(err, existingGroup) {
if (err) {
res.json({'message': err });
} else if (existingGroup) {
var group = existingGroup;
Group.findOne({'_id': req.params.group_id })
.execQ()
.then(function(existingUser) {
var friendphoneNumber = req.body.friendphoneNumber.split(',');
var friends = [];
console.log('existingUser', friendphoneNumber);
async.each(friendphoneNumber, function(phonenum, callback) {
var phonenum = phonenum.split("\'")[0];
console.log('phonenum', phonenum);
User.findOne({'phoneNumber': phonenum })
.execQ()
.then(function(existingFriend) {
if (existingFriend === null) {
friends.push({'details': {'phoneNumber': phonenum } });
} else {
friends.push({'details': existingFriend });
}
})
.catch(function(err) {
console.log('err', err)
friends.push({'details': {'phoneNumber': phonenum } });
})
.done(function() {callback(); });
}, function(err) {
friends.push({'details': {'phoneNumber': friendphoneNumber } });
existingGroup.friends = friends;
existingGroup.save();
// existingGroup.update({ '_id': req.params.group_id},{ "$set": {'friends': req.body.friendphoneNumber} } , function(err) {
// existingGroup.update({'_id': req.params.group_id}, {update[[, 'friends': req.body.friendphoneNumber]}, callback]);
existingGroup.update(function(err) {
if (err) {
res.json({message: err });
} else {
res.json({success: 1, message: 'Group updated', updatedGroup: existingGroup });
}
});
});
})
.catch(function(err) {
res.json({success: 0, message: 'user id Not Match. Please try again'});
}).done(function(events) {});
} else {
callback();
}
});
});
I solved it (with some help though):
async.each(friendphoneNumber, function(phonenum, callback) {
phonenum = phonenum.split("\'")[0];
console.log('phonenum', phonenum);
User.findOne({
'phoneNumber': phonenum
})
.execQ()
.then(function(existingFriend) {
if(existingFriend === null) {
friends.push({
'details': {
'phoneNumber': phonenum
}
});
} else {
friends.push({'details': existingFriend});
}
})
.catch(function(err) {
console.log('err', err)
friends.push({
'details': {
'phoneNumber': phonenum
}
});
})
.done (function() {
callback();
});
}, function(err) {
friends.push({
'details': {
'phoneNumber': friendphoneNumber
}
});
group.friends = friends;
Group.update({ '_id': req.params.group_id}, { $set: { 'friends': {'details': req.body.friendphoneNumber } } }, {safe: true, upsert: true}, function (err, user) {
if (err) {
res.json({
message: err
});
} else {
res.json({
success: 1,
message: 'Group updated',
group: group
});
}
});
});
})
.catch(function(err) {
res.json({
success: 0,
message: 'user id Not Match. Please try again'
});
})
.done(function(events) {
});
}
else {
callback();
}
});
I am trying to update user.task.fixitItem, where the Task schema is embedded within the User schema.
Using this get,
app.get('/api/tasks/:id/edit', isAuthenticated, function (req, res) {
console.log('*** testing route GET /api/tasks/:id/edit', req.params);
User.findOne({'task._id': req.params.id})
.select('task.$')
.exec(function(err, user) {
if(!user) {
res.statusCode = 404;
return res.send({ error: 'Not found' });
}
if(!err) {
return res.render('tasks/edit', {task: user.task[0] });
} else {
res.statusCode = 500;
console.log('Internal error(%d): %s', res.statusCode, err.message);
return res.send({ error: 'Server error' });
}
}
);
});
How do you write the put to update the data?
You need to use the update method with $set
User.update(
{ 'task._id': req.params.id },
{ $set: { 'task.$.fixitItem': 'new value' }},
function(err, user) {
}
);