Get single document in express doesn't jumps to catch - node.js

I have the following express code. If I try to get a document with a non-existent id, I get nothing. The problem is that I get 200 as response status and I don't get the Failed message. The code jumps every time into "then".
const Mymodel = require('../model/Mymodel');
const Single = (req, res) => {
const id = req.params.id;
Mymodel.findById(id)
.then(result => {
res.send(result);
})
.catch(err => {
console.log(err);
res.status(404).send({"Failed": "Document not found"});
});
}

your finding query response is null so this is not an error. if you send res.status(404).send({"Failed": "Document not found"}); response for not found use this.
const Mymodel = require('../model/Mymodel');
const Single = (req, res) => {
const id = req.params.id;
Mymodel.findById(id)
.then(result => {
if(result){
res.send(result);
}else{
res.status(404).send({"Failed": "Document not found"});
}
})
.catch(err => {
console.log(err);
res.status(404).send({"Failed": "Document not found"});
});
}

Related

MongoDB insertMany() working fine and data is saving to the Database, but gives 400 Bad request error

This is my node JS
const router = require("express").Router();
const Posts = require("../../models/vendorProjectsDatabaseExcellUpload");
router.post('/vendorProjectsDatabasesExcell/save',(req,res) => {
const newPost = req.body;
// console.log(newPost);
// Posts.insertMany(newPost).then((err) =>{
// if(err){
// return res.status(400).json({
// error:err
// });
// }
// return res.status(200).json({
// success:"Project Details Added Successfully"
// });
// });
try {
const options = { ordered: true };
const result = Posts.insertMany(newPost, options).then((err) =>{
if(err){
return res.status(400).json({
error:err
});
}
return res.status(200).json({
success:"Project Details Added Successfully"
});
});
console.log(`All documents were inserted`);
} finally {
console.log('done');
}
});
module.exports = router;
This is my React.js
const uplaodHandler = async (e) => {
// const uplaodHandler = (e) => {
e.preventDefault();
const newPost = items;
// console.log(newPost);
await axios
.post('http://localhost:8072/vendorProjectsDatabasesExcell/save', newPost)
.then((result) => {
alert(result);
alert('New Project Added now');
// navigate('/dashboard/DatabasesUploadProjectFilesVendorProjects', { replace: true });
console.log(newPost);
})
.catch((error) => {
console.log(error);
// console.log(error.response.data);
// console.log(error.response.status);
// console.log(error.response.headers);
});
};
Other post and put request in other pages of the same app is works fine without any error.
In here also the json data array post to the mongo DB without any issue. Only problem is it is giving the bad request 400 error.
Just modify this part:
const result = Posts.insertMany(newPost, options)
.then((res) =>{
return json({success:"Project Details Added Successfully"});
}).catch((err) => {
return json({error:err});
});

MongoDB not getting delete request

CLIENT:
const handleDelete = (id) => {
console.log(id);
axios.delete(`http://localhost:3001/delete`, {id})
.then(res => console.log(err)})
.catch(err => console.log(err))
}
CONSOLE LOGS THE ID correctly: vv17OZpdGkMwNEv0
SERVER:
cartRoutes.route("/delete").delete((req, res) => {
console.log(req.body);
let db_connect = dbo.getDb("cart");
let myquery = { id: req.body.id };
db_connect.collection("cart").deleteOne(myquery, function (err, obj) {
if (err) throw err;
// console.log("1 document deleted");
});
});
CONSOLE LOGS OUT {}
This is basically copied from MongoDB document, the server(2nd block of code) does not recognize the call from the client. I know that the mongo code works because if I manually put the id in the 'myquery' variable, the item is deleted in the database
Why is that? MongoDB doc has it set up like below which I've tried and still the req.body returns '{}'
Figured it out, not sure if using params is the correct way/best practice
Client
const handleDelete = (e, id) => {
e.preventDefault();
axios.delete(`http://localhost:3001/delete/${id}`)
.then(res => console.log(res))
.catch(err => console.log(err))
}
Server
cartRoutes.route("/delete/:id").delete((req, res) => {
let db_connect = dbo.getDb("cart");
let myquery = { id: res.req.params.id };
db_connect.collection("cart").deleteOne(myquery, function (err, obj) {
if (err) throw err;
// console.log("1 document deleted");
});
});

Why does my register user post request fail with a 500 error?

I'm building an app with React and Node/Express, and I'm having trouble with my register user function. The data I am passing in is correct, and other endpoints work fine. The register one keeps returning a 500 error and I can't figure out why.
This is my request:
console.log(values)
axios
.post(
'https://foodtrackr-backend.herokuapp.com/api/register',
values
)
.then(res => {
console.log('res.data', res.data);
})
.catch(error => {
console.log('nope');
console.error(error);
});
};
and this is my endpoint:
router.post('/register', async (req, res) => {
let user = req.body;
const newUser = await Users.add(user);
try {
if (newUser) {
res.status(201).json(user);
} else res.status(404);
} catch (error) {
res.status(500).json('noooooo');
}
});
and this is my model:
function findById(id) {
return (
db('users')
.where({ id })
.first()
);
}
async function add(user) {
const [id] = await db('users').insert(user, 'id');
return findById(id);
}
Any help would be appreciated!

Unable to pull record from array

I am trying to remove an item from an array of objects by using Mongoose 'pull'. I am getting a status code of 200 and apparently everything is fine but the record is not actually removed? The userId in mongo db looks like:
userId: ObjectId("6b275260a6g58308e510721b")
exports.putDislike = (req, res, next) => {
const productId = req.body.productId;
const userId = req.body.userId;
Product.findById(productId)
.then(product => {
if (!product) {
return next(new Error('Product not found.'));
}
product.requests.pull(userId)
return product.save()
.then(result => {
res.status(200).json({ message: "Item request removed." });
})
})
.catch(err => {
res.status(500).json({ message: "Removing request failed." });
});
};
I'm not sure you are using pull correctly, check out this link https://docs.mongodb.com/manual/reference/operator/update/pull/
According to that, i think your code should be somehing like the example below:
exports.putDislike = (req, res, next) => {
const productId = req.body.productId;
const userId = req.body.userId;
Product.update(
{ "_id": productId },
{ $pull: { requests: {userId: userId} } })
.then(result => {
res.status(200).json({ message: "Item request removed." });
})
.catch(err => {
res.status(500).json({ message: "Removing request failed." });
});
};

ExpressJS - populate before save asyc await

I want to populate user in Feed model, and i cant do that, this is what i tried
router.post('/', async (req, res) => {
const newFeed = new Feed(req.body);
try {
const article = await newFeed.populate('created_by');
const finalArticle = await newFeed.save();
res.status(200).json({
success: true,
message: "Successfully created.",
data: finalArticle
})
} catch (err) {
next(err)
}
});

Resources