Node JS: Data is not reaching next .then() - node.js

I am not able to change the status from o to 1. The server is returning 500 . I don't know what is wrong I have done everything fine why its not pushing.
function changeAdminStatus(req, res, next){
getSuperAminById(req.params.id)
.then(function(data){
if(data.account.status == 1)
{
console.log(data);
Admin.findByIdAndUpdate(data._id, {
$push: {
'account.status' : 0
}
}, function(err, doc) {
if (err) {
res.sendStatus(500);
}
else if(doc) res.sendStatus(200);
else res.sendStatus(200);
}
);
}

in second line use return will take the result to the next .then
function changeAdminStatus(req, res, next){
return getSuperAminById(req.params.id)
.then(function(data){
if(data.account.status == 1)
{
console.log(data);
Admin.findByIdAndUpdate(data._id, {
$push: {
'account.status' : 0
}
}, function(err, doc) {
if (err) {
res.sendStatus(500);
}
else if(doc) res.sendStatus(200);
else res.sendStatus(200);
}
);
}

Are you setting MongoDB like that
$push: {
'account.status' : 0
}
instead
$push: {
'account' :{ 'status' : 0 }
}

Related

Sending a POST request in Postman set to send a certain status sends the default status

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();
});
});
});

how can I call PUT after GET in Express

Requesting GET then PUT in Postman works as expected, although I don't see how to programmatically do this in node.
example:
Request GET localhost:3000/orders/Asia
returns 50 stock
Request PUT localhost:3000/orders/Asia/40
returns 10
app.get('/orders/:coffeeid', function(req, res) {
db.collection('coffees').find({'name': req.params.coffeeid}).toArray((err, result) => {
if (err) return res.send(500, err)
var data = {
"orders": {
"name": result.coffeeid,
"stock": result.stock
}
};
res.json(result);
})
})
app.put('/orders/:coffeeid/:quantity', function(req, res) {
db.collection('coffees').find({'name': req.params.coffeeid}).toArray((err, result) => {
if (err) return res.send(500, err)
orders = {
"name": req.params.name,
"quantity": req.params.quantity
};
console.log(result[0].stock, orders.quantity, orders.quantity <= result[0].stock) // resolvido
console.log(orders.quantity)
if (Number(orders.quantity) <= Number(result[0].stock) ) {
result[0].stock = result[0].stock - orders.quantity
db.collection('coffees').updateOne({'name': req.params.coffeeid}, result[0], function(err, result) {
console.log('Order dispached. Thank you');
res.json(result);
res.render('orders.ejs', {orders: result, success: false})
});
}
else {
console.log('There isnt enough in stock. Will dispach ASAP');
res.json({error: true});
}
})
})
How can I programmatically call update after "getting" the stock value from get?
Thanks
If I understand correctly, the answer will be is instead of declaring anonymous function for PUT request, you can do this
`
const whatEverYouWant =function(req, res) {
db.collection('coffees').find({'name': req.params.coffeeid}).toArray((err, result) => {
if (err) return res.send(500, err)
orders = {
"name": req.params.name,
"quantity": req.params.quantity
};
console.log(result[0].stock, orders.quantity, orders.quantity <= result[0].stock) // resolvido
console.log(orders.quantity)
if (Number(orders.quantity) <= Number(result[0].stock) ) {
result[0].stock = result[0].stock - orders.quantity
db.collection('coffees').updateOne({'name': req.params.coffeeid}, result[0], function(err, result) {
console.log('Order dispached. Thank you');
res.json(result);
res.render('orders.ejs', {orders: result, success: false})
});
}
else {
console.log('There isnt enough in stock. Will dispach ASAP');
res.json({error: true});
}
})
}
app.get('/orders/:coffeeid', function(req, res) {
db.collection('coffees').find({'name': req.params.coffeeid}).toArray((err, result) => {
if (err) return res.send(500, err)
var data = {
"orders": {
"name": result.coffeeid,
"stock": result.stock
}
};
yourPutRequest(req,res) //
res.json(result);
})
})
app.put('/orders/:coffeeid/:quantity',whatEverYouWant)
`

why my updateOne mongodb does not return anything?

I have this code:
MongoClient.connect(config.mongoURL, {useNewUrlParser: true}, (err, db)=> {
if (err) {
console.log("Err", err)
cb(-1)
}
else {
var con = db.db('englishAcademy')
try {
con.collection("sound").updateOne({"_id": new ObjectID(sndId)}, {
$set: {
"snd_title": info.snd_title,
"snd_type": info.snd_type,
"snd_url": info.snd_url,
"snd_lsnId": info.snd_lsnId,
"snd_lvlId": info.snd_lvlId,
"snd_order": info.snd_order
}
}), (err, doc) => {
console.log("result")
if (err) {
console.log(err)
cb(-1)
}
else {
console.log(doc)
let result = 'row affected'
cb(doc)
}
}
}
catch (e) {
console.log(e)
}
}
})
could anyone please tell me what is wrong with my code?the updateOne function does not return anything.but my mongo database gets updated.
EDIT :
I have done this so far and it did not worked.could anyone please help?I used assert no success.I used new :true, no success.I used finde and update ,no success
let infor = {
"adm_name": info.adm_name,
"adm_username": info.adm_username,
"adm_password": info.adm_password
}
con.collection("admins").findOneAndUpdate({"_id": new ObjectID(admId)}, {
$set: infor
},{new:true} ), (err , result) => {
console.log("result")
if (err) {
console.log(err)
assert.equal(err, null);
cb(-1)
}
else {
let result = 'row affected'
assert.equal(1, result.result.n);
}
set new: true
MongoClient.connect(config.mongoURL, {useNewUrlParser: true}, (err, db)=> {
if (err) {
console.log("Err", err)
cb(-1)
}
else {
var con = db.db('englishAcademy')
try {
con.collection("sound").updateOne({"_id": new ObjectID(sndId)}, {
$set: {
"snd_title": info.snd_title,
"snd_type": info.snd_type,
"snd_url": info.snd_url,
"snd_lsnId": info.snd_lsnId,
"snd_lvlId": info.snd_lvlId,
"snd_order": info.snd_order
},{new: true}
}), (err, doc) => {
console.log("result")
if (err) {
console.log(err)
cb(-1)
}
else {
console.log(doc)
let result = 'row affected'
cb(doc)
}
}
}
catch (e) {
console.log(e)
}
}
})
Try this way ..
collection.findOneAndUpdate(
{"_id": new ObjectID(sndId)},
$set: yourData },
{ new: true },
function (err, documents) {
res.send({ error: err, result: documents });
}
);
Now you can return newData in cb.

how to get multiple collection data in single get method using mongoose in node js

router.post('/user', function (req, res) {
try {
MongoClient.connect("mongodb://test123:test123#localhost:27017/test", function (err, db) {
db.collection('user').findOne({ _id: req.body.UserId }, function (err, founddata) {
if (err) {
} else {
if (founddata) {
db.collection('project').find({ userId: founddata._id }, function (err, data) {
if (err) {
console.log(err);
} else {
console.log(data)
}
})
}
}
})
})
} catch (e) {
console.log(e)
}
})
I have tried many time but i geting error for second query is not run.output is null value.

Value not being updated in DB, node.js and mongoose

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');
});

Resources