Update database - node.js

I am struggling to get .put or .patch to work. when using postman I get the call back returned but the values are not updated in my database on robo 3t. I have tried fixing the deprecation warning and using updateOne, updateMany.
This will fix the deprecation warning but will not update the database. Here is the code before i fix the deprecation. Any ideas what I'm doing wrong?
////////////////////Request Targeting A Specific Article///////////////////////
app.route("/articles/:articleTitle")
.get(function(req, res){
Article.findOne({title: req.params.articleTitle}, function(err, foundArticle){
if (foundArticle) {
res.send(foundArticle);
} else {
res.send("No articles with that title.");
}
});
})
/////////PUT PROBLEM MUST BE FIXED /////////////
.put(function(req, res){
Article.update(
{title: req.params.articleTitle},
{title: req.body.title, content: req.body.content},
{overwrite: true},
function(err){
if(!err){
res.send("succesfully updated");
}
}
);
})
///////PATCH PROBLEM MUST BE FIXED ///////////
.patch(function(req, res){
Article.update(
{title: req.params.articleTitle},
{$set: req.body},
function(err){
if(!err){
res.send("Successfully updated article.");
} else{
res.send(err);
}
}
);
});

app.route("/articles/:articleTitle")
.get((req, res) => {
Article.findOne({ title: req.params.articleTitle }, (err, result) => {
if (result) {
res.send(result);
} else {
res.send("err");
}
});
})
.put((req, res) => {
Article.replaceOne(
{ title: req.params.articleTitle },
{ title: req.body.title, content: req.body.content },
{ overwrite: true },
(err) => {
if (err) {
res.send("There is some error");
} else {
res.send("Updated successfully");
}
}
);
})
.patch((req, res) => {
Article.updateOne(
{ title: req.params.articleTitle },
{ $set: req.body },
(err) => {
if (err) {
res.send("There is some error");
} else {
res.send("Updated successfully");
}
}
);
});
Try this!! this will work fine.

Related

Mongoose not picking up on callback variables for render

app.get("/users/:id", function (req, res) {
User.findById(req.params.id, function (err, foundUser) {
if (err) {
console.log(err)
} else {
console.log(foundUser)
}
})
Item.countDocuments({ UID: req.params.id }, function (err, itemCount) {
if (err) {
console.log(err)
} else {
console.log(itemCount)
}
})
Item.find({ UID: req.params.id }, function (err, foundItems) {
if (err) {
console.log(err)
} else {
console.log(foundItems)
}
})
res.render("users/show", { user: foundUser, newListItems: foundItems, itemCount: itemCount})
For some reason this wont render and keeps saying that the variables dont exist despite the callbacks above. Using EJS for render.
I may be reading the code incorrectly, but aren't the callback variables out of scope for the res.render method?
You may need to return the callbacks from each of the Mongoose queries and store them in variables that are within the scope of the res.render method.
As suggested by Richie, you cannot access the variables from.inside the callbacks in the outer scope
app.get("/users/:id", function (req, res) {
User.findById(req.params.id, function (err, foundUser) {
if (err) { console.log(err) }
else {
console.log(foundUser)
Item.countDocuments({ UID: req.params.id }, function (err, itemCount) {
if (err) { console.log(err) }
else {
console.log(itemCount)
Item.find({ UID: req.params.id }, function (err, foundItems){
if (err) { console.log(err) }
else {
console.log(foundItems);
res.render("users/show", { user: foundUser, newListItems: foundItems, itemCount: itemCount})
}
});
}
});
}
});
});
Notice that I've put the res.render method inside the callbacks so that the variables are available to it.
EDIT
As suggested by Marcel Djaman, You should probably use async/await to make code more readable. Read more about async/await here
app.get("/users/:id", async function (req, res) {
try {
const foundUser = await User.findById(req.params.id);
console.log(foundUser)
const itemCount = await Item.countDocuments({ UID: req.params.id });
console.log(itemCount)
const foundItems = await Item.find({ UID: req.params.id });
console.log(foundItems);
res.render("users/show", { user: foundUser, newListItems: foundItems, itemCount: itemCount});
} catch(err) {
console.error(err)
}
});
You can notice how much simpler this code is than the one above it.

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)
`

find and modify obejct in mlab collection by _id with nodejs

i am posting an object to update the current one. Searching by id and replacing it. For some reason i don't get errors but the mlab object is not updated. Am i missing something?
app.post("/api/updateCheck", function (req, res) {
console.log('updating', req.body);
conn.collection("checks").findAndModify({
_id: req.body._id
}, {$set: req.body}, {}, function(err,doc) {
if (err) { console.log(err) }
else { console.log("Updated"); }
});
});
got it. updateOne seems to work. I am posting a check object and retrieving id from it to search the collection and update content accordingly.
// modify content
app.post("api/updateCheck", function(req, res) {
console.log("updating", req.body);
conn.collection("checks").updateOne(
{
_id: new ObjectId(req.body._id)
},
{
$set: {
content: req.body.content
}
},
function(err, doc) {
if (err) {
console.log("error", err);
} else {
console.log('success', doc.modifiedCount);
console.log('??', doc.matchedCounted);
res.status(200).json(res.body);
}
}
);
});

How to update subdoc data in Mongoose

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

I cant push array into a mongoose schema

This is my controller, one form send here the data:
exports.addrepair = function(req, res, next){
Person.findById( req.body.id, function (err, Person) {
Person.update({id: req.body.id},
{$pushAll: {
problem: req.body.problem
, solution: req.body.solution
, date_on: Date.now()
}}
,{upsert:true},function(err){
if(err){
console.log(err);
}else{
console.log("Added");
}
})
})
}
the schema is:
var Person = new Schema ({
name: String,
Repair: [
problem: String,
solution: String,
date_on: Date
]
})
and cant push any repair to Person. With console.log i can see all works but not the push.
This works for me now. Thanks Peter Lyons
Person.findByIdAndUpdate(req.body.id,
{ $push:
{ repair:
{ problem: req.body.problem
, solution: req.body.solution
, date_on: Date.now()
}
},
function(err){ if(err){
console.log(err)
} else {
console.log('Added')
}
});
exports.addrepair = function(req, res, next) {
//The Person.findById you had here was unnecessary/useless
Person.findByIdAndUpdate(req.body.id,
{
Repair: {
$push: {
problem: req.body.problem,
solution: req.body.solution,
date_on: Date.now()
}
}
},
//You don't want an upsert here
function(err){
if(err){
console.log(err);
}else{
console.log("Added");
}
}
)
}

Resources