Mongoose and postman error in method model.find() - node.js

This is the screenshot of my Javascript codeThis is the screenshot of postman
app.get("/students/:id",async(req,res)=>{
try {
const _id=req.params.id;
const studentData=await Student.findById(_id);
console.log(studentData);
if(!studentData){
return res.status(404).send();
}else
res.send(studentData);
}
catch(err) {
res.send(err);
}
});
For this id case I am able to find the value in database.
But if I am using model.find({name:name}) as per screenshot ,I am getting some error in postman.Can anyone help me to solve the issue.

it seems you have two conflicting routes, from your code above I see you have a get route for /student/:id and from the screenshot you have another get route for /student/:name these two routes cannot exist together as express is going to pick the first one you defined.
I suggest changing them to /student/id/:id and /student/name/:name.

Related

Express server returns 200 for routes that have not even been defined

I have been facing a weird thing for several days and I had no luck of solving that so far. The problem is I have a React.js frontend , Node Express.js backend and MongoDB, when I'm making requests to /api/users/update-pwd with proper parameters using axios, it doesn't update the password, but it returns 200. Then, I tried some routes such as /api/users/psosp. To my surprise, It also returned 200. I couldn't find the reason for that. Any helpful tip is highly appreciated.
Axios.post("/users/update-password",{
password: n_pwd
}).then(
res => {
alert("Password Updated")
}
).catch(err => {
console.log(err)
alert("An error occured")
})
Make sure that you don't have code like this in your backend.
router.post('/users/:userId',(req,res)=>{
// some operations
res.send();
});
router.post('users/update-password',(req,res)=>{
// some operations
res.send();
});
What above does is that it doesn't matter whatever you use in place of * /users/*/
the first route will be called by default
and also make sure that you did not use
app.use('*',(req,res)=>{
// some operations
res.send();
})
For any API call irrespective of the path the above code will be called.

why does this post implementation return 404 in node/express?

The following URL provides a pretty good walkthrough of how to wire up a node/express implementation to read from Google Cloud Platform Cloud SQL:
https://medium.com/#austinhale/building-a-node-api-with-express-and-google-cloud-sql-9bda260b040f
I implemented the steps in this article and my local implementation is working as expected. However, this URL doesn't cover how to wire up inserts/updates. Based on some googling, I came up with the following implementation for a post/insert:
// POST method route
app.post('/users', function (req, res) {
var post = { FirstName: req.FirstName, LastName: req.LastName };
var query = connection.query('INSERT INTO User SET ?', post, function (error, results, fields) {
if (error){
console.log(error.message);
}
});
})
I'm POST-ing the following request from Postman as raw JSON:
http://localhost:3000/users/
{
"FirstName":"John",
"LastName":"Smith"
}
However, the response status is 404 Not Found. The standard GET is working as expected though. Any idea what I might be doing wrong here? Also, I'm new to Node/Express. What's the easiest way to get started debugging? For example, is there a recommended plugin for CDT that I can use for this? The sample code that I used for the GET used console.log("message") but when I tried this approach, nothing appeared to be written out to the node console window or to CDT?

How to catch and save all errors in strapi?

I'm trying to integrate my strapi application with sentry, for which I will need to write a middleware. Use the following documentation: https://strapi.io/documentation/3.0.0-beta.x/advanced/middlewares.html I was able to create a custom middleware with the following:
module.exports = strapi => {
return {
initialize() {
strapi.app.use(async (ctx, next) => {
try {
await next();
} catch (error) {
Sentry.captureException(error)
}
});
}
};
};
However, doing so is preventing strapi to print out the errors to console the usual way but the error is captured by sentry application.
So, my question is: How do I capture the error "seamlessly" and send it to a third party application, at the same time not hinder with the default functioning and error logging of the strapi to console.
Any help would be greatly appreciated!
Thanks :)
EDIT: I figured out that all strapi errors are accessible at the "boom" middleware as pointed out in this file: https://github.com/strapi/strapi/blob/6309af25c921640cb76aeeda463e55db1eb53ef1/packages/strapi/lib/middlewares/boom/index.js#L69
Answer has been given by the authors here: https://github.com/strapi/strapi/issues/4071

How to set Routes for APIs

I am building an API to manage meetups with nodeJS. I have build an endpoint with the route "/meetups/:id/" to fetch a specific meetup record by its id. And then I want to fetch all the upcoming meetup records and I tried to use "/meetups/upcoming/" but when I query it, I get the not found error (404). It seems like the second route is not recognised.
Here is the code defining the two routes
the request from postman
Any help on how can I handle that?
Thanks.
Route is '/api/v1/meetups/upcoming/all'. Move res.status outside the map function.
EDIT: you'll have to change the route which has to be different from api/v1/meetups/:id. Reason is when route '/api/v1/meetups/upcoming' is requested express sees it as the same route as before and takes 'upcoming' as the parameter.
app.get("/api/v1/meetups/upcoming/all", function(req, res) {
var today = new Date();
var upcomings = db.meetups.map(function(meetup) {
if(meetup.happeningOn > today) {
return meetup;
}
});
res.status(200).send({
status: 200,
data: upcomings
});
});
You need to move the res.status piece outside of the const upcomings definition.

Accessing response headers using NodeJS

I'm having a problem right now which I can't seem to find a solution to.
I'm using Uservoice's NodeJS framework to send some requests to UserVoice regarding Feedback posts. A problem I've run into are ratelimits so I want to save the header values X-Rate-Limit-Remaining, X-Rate-Limit-Limit and X-Rate-Limit-Reset locally. I've made a function for updating and getting that value and am calling it like this:
var content = "Test"
c.post(`forums/${config.uservoice.forumId}/suggestions/${id}/comments.json`, {
comment: {
text: content
}
}).then(data => {
rl.updateRL(data.headers['X-Rate-Limit-Limit'],data.headers['X-Rate-Limit-Remaining'],data.headers['X-Rate-Limit-Reset'])
When running this code I get the error Cannot read property 'X-Rate-Limit-Limit' of undefined.
This is not a duplicate, I've also tried it lowercase as described here but had no luck either. Thanks for helping out!
EDIT:
The function takes the following parameters:
module.exports = {
updateRL: (lim, rem, res) {SAVING STUFF HERE}
}
It is defined in the file rates.jsand is imported in the above file as const rl = require('../rates').

Resources