Unable to make put request using node js. Mongoose - node.js

i am just looking to make an PUT request using Mongoose database. But Its Unable to make any request. I am using postman to pass the data, but no response.
script.js
app.route("/articles/:articleTitle")
.put(function (req, res) {
Article.updateMany(
{ title: req.params.articleTitle },
{ title: req.body.title, content: req.body.content },
{ overwrite: true },
function (err) {
if (!err) {
res.send("Successfully Updated The Data !");
}
}
);
});
here is the code i am using to pass the PUT request in my localhost server but unable to do so.
No Response Here Is The Result

You don't send any response in case of an error, causing the request to hang and never return. Change it to e.g.:
function (err) {
if (!err) {
res.send("Successfully Updated The Data !");
} else {
console.log(err);
res.status(500).send("Update failed due to error " + err.message);
}
}

app.route("/articles/:articleTitle")
.put(async function (req, res) {
try {
await Article.updateMany(
{ title: req.params.articleTitle },
{ title: req.body.title, content: req.body.content },
{ overwrite: true },
)
res.status(200).send("Successfully Updated The Data !");
} catch (err) {
res.status(500).send("Update failed due to error " + err.message);
}
});

Related

Update database

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.

Err: Cannot POST /api/success

I am trying to send a POST request but it seems like the route isn't working based off the error. However, I get the value of req.body.entries logged in my console so it has to be working. When I send a GET request the browser sits and loads. The same thing happens in Postman. I am trying to figure out why I get an error on the POST request and the GET request sits. Thank you in advance.
index.js
const successRoute = require("./routes/success");
app.use("/api/success", successRoute);
success.js
router.get(
"/",
basicAuth({
users: { username: "password" },
}),
async function (req, res) {
try {
const entry = await Entry.find({});
res.sendStatus(entry);
} catch (err) {
res.sendStatus({ msg: "oops something went wrong" });
}
}
);
router.post("/", async (req, res, next) => {
try {
//console.log(req.body);
const { store, entries } = req.body;
Entry.findOneAndUpdate(
{ _id: store },
{ $set: { entries: +req.body.entries } },
{ new: true },
(err, doc) => {
if (err) {
console.log(err);
}
console.log(req.body.entries);
next();
}
);
} catch (err) {
const entry = new Entry({
_id: store,
entries: req.body.entries,
});
await entry.save();
res.sendStatus(200);
next();
}
});
I think the problem is, inside your router.post(), you're not sending any response, you only call next(). I don't see any next route for the request.
I'd recommend something like this:
router.post("/", async (req, res, next) => {
try {
//console.log(req.body);
const { store, entries } = req.body;
Entry.findOneAndUpdate(
{ _id: store },
{ $set: { entries: +req.body.entries } },
{ new: true },
(err, doc) => {
// throw the error and catch later
if (err)
throw err;
console.log(req.body.entries);
// send response instead of calling next()
res.sendStatus(200);
}
);
} catch (err) {
const entry = new Entry({
_id: store,
entries: req.body.entries,
});
await entry.save();
// send response
res.sendStatus(200);
// next(); // don't call next unless next route defined
}
});

mongoose findOneAndUpdate returns twice with null on first?

this is my code:
router.post('/update_todo', async (req, res) => {
const { todoId, userId, complete } = req.body;
try {
const todo = await Todo.findOneAndUpdate(
{ _id: todoId, userId },
{ $set: { complete: !complete } },
{ new: true } // return latest
).populate('userId', '_id');
console.log('todo pdated', todo)
res.json({ todo })
} catch (error) {
res.status(400).json({ error })
}
})
when i try to log, it's returning twice?
todo pdated null
todo pdated { complete: true,
_id: 5c003223ec8c1350b8c77b4f,
text: 'wearasdasd asd 2222',
userId: { _id: 5bf3b0b676bcc8176422e94e },
createdAt: 2018-11-29T18:38:27.156Z,
updatedAt: 2018-11-29T23:31:57.022Z,
__v: 0 }
what is causing this code to return twice when i am using async/await?
try this :
router.post('/update_todo', async (req, res) => {
const { todoId, userId, complete } = req.body;
try {
Todo.findOneAndUpdate({_id: todoId,userId:userId},{$set:{complete: !complete}}, {new: true}, (err, doc) => {
if (err) {
console.log("Something wrong when updating data!");
}
console.log('todo updated', doc)
res.json({ doc })
});
} catch (error) {
res.status(400).json({ error })
}
})
I have a guess, although your question lacks enough data to be sure: I don think it is an issue with async/await, but your code is running twice because browser makes Preflight OPTION request:
... "preflighted" requests first send an HTTP request by the OPTIONS
method to the resource on the other domain, in order to determine
whether the actual request is safe to send.
To prevent that, I suggest this piece of code in a CORS scenario that returns the OPTIONS request before the system reaches out your business logic:
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", '*');
...
if (req.method === 'OPTIONS') {
res.sendStatus(200);
}
else {
next();
}
});

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

Cannot process POST request in Sails.js correctly

I'm trying to add comments functionality into my Sails.js blog application. However, I don't seem to write my controller action correctly.
When I submit the comment form, the page starts to reload, but does not finish reloading.
Here's my controller code:
const gravatar = require('gravatar');
module.exports = {
blog: (req, res) => {
Post.find({}).exec((err, posts) => {
if (err) {
res.send(500, { error: 'Database Error' });
}
res.view('all-posts', { posts });
});
},
singlePost: (req, res) => {
Post.findOneBySlug(req.params.slug).exec((err, post) => {
if (err) {
res.send(500, { error: 'Database Error' });
}
res.view('single-post', {
post,
gravatar: gravatar.url
});
});
},
addComment: (req, res) => {
const {
name, comment, email,
url, slug,
} = req.allParams();
Post.findOneBySlug(slug).exec((err, post) => {
if (err) {
return res.send(500, { error: 'Database Error' });
Comment.create({
body: comment, name, email, website: url
}).exec((error, comment) => {
if (error) {
return res.send(500, { error: 'Database Error' });
}
console.log(comment);
post.comments.addComment({slug, comment});
post.save();
res.redirect(`/${slug}`);
});
}
});
return false;
},
};
And here's my routes.js file:
module.exports.routes = {
'get /blog': 'BlogController.blog',
'get /:slug': 'BlogController.singlePost',
'post /:slug/new-comment': 'BlogController.addComment'
};
And this is my model Post.js
module.exports = {
identity: 'Post',
attributes: {
title: {
type: 'string',
required: true,
unique: true
},
body: {
type: 'string'
},
categories: {
type: 'string',
required: true
},
imageUrl: {
type: 'string'
},
comments: {
collection: 'Comment',
via: 'post'
},
slug: {
type: 'slug',
from: 'title',
blacklist: ['search', 'blog', 'contacts']
}
},
addComment: (options, cb) => {
Post.findOneBySlug(options.slug).exec((err, post) => {
if (err) return cb(err);
if (!post) return cb(new Error('Post not found.'));
post.comments.add(options.comment);
post.save(cb);
})
},
connection: 'mongodb'
};
So, when I submit the comment form on the /:slug page, nothing actually happens accept the page tries to reload. And in the database nothing gets saved as well.
The form parameters get sent from the form, so on the client side everything should be fine.
How how I approach this post request correctly?
You need to add return statement before each res.send(500, ...); call, because currently, in the case of the error, your code tries to send the response twice, and client doesn't get the response with the actual error:
if (err) {
return res.send(500, { error: 'Database Error' });
}
... rest code
I suspect, that the reason why nothing is saved in db is invalid parameters in request body.

Resources