how to get records from mongodb through node js - node.js

Here In my mongo collection I have few records. I am writing an API in node js where I pass the ID in request body. My API have to take ID from request body and need to fetch it's whole records in response. but I am getting empty array.
My mongo collection record:
[{ accountId:"a1",name:"test"}]
My Node js code approach:
exports.getById = async (req) =>{
let id = `"` + req.body.accountId +`"`;
let accountId = await db.collection('account-details').find({id}).toArray();
return accountId
}
In request body, I am passing accountId as :
{
"accountId":"a1"
}
The ID is in the form of string. When I am trying to fetch whole records with the provided ID through my API, I am getting response as []. Can anyone please help me on this

You cannot send a body with an HTTP GET, therefore it will not be available in the req object, so req.body.accountId will be undefined and id will be an empty string.
You need to use POST (or PUT) to send body data.
But the more usual solution in your situation is to use GET with dynamic routing, where you add the id to the route e.g.: http://example.com/api/accounts/1234
If you use Express, in your router you need to add the route api/accounts/:id to your router. The id will be available in your code as req.params.id.
See Express docs. For other frameworks this will be something alike.
Hope this helps.

Related

NodeJS/ExpressJS : Access URL of the post request

In a project I'm working on, I need to access the parameters of the url in the backend.
I tried this based on what I found on the internet, but it doesnt seem to work.
//url = "/getDocs?num=15"
router.get("/getDocs", function(req,res,next){
console.log(req.body.num);
res.redirect("/documents");
}
Please help
In url it seems you are using query string which can be accessed as: request.query.num
If you are passing only params in url like getDocs/:num value then it can be accessed as: request.params.num
Simple way of doing this is querying the req object with the property name:
router.get("/getDocs", function(req,res,next){
const name = req.query.name;
res.redirect("/documents");
}
If you sending as a part of route, you can use this:
router.get("/getDocs/:id", function(req,res,next){
const id = req.params.id;
res.redirect("/documents");
}
For more details check here.

Postman Mongoose response empty array

I am working on an app that responses are set like
req.data = data
I created a new endpoint, and if I console.log the data, I can see that mongoose is retriving the data. But postman is showing an empty array in the response
Also if I add
res.json(data)
Postman will show the json, but I don't want to change the app style
Probably I forgot to set something
Usually i use express to make API responses as the following :
app.get('/',(req,res)=>{
// some code goes here that will return DATA
res.status(200).json(DATA) // And This line will return a JSON file to postman
})
NOTE : use req.something to handle your incoming data, res.something to make a response to the client.

What to do when NodeJS rest api is sendind status 404 while using parameters?

I am having a strange problem while writing my api. I am using Nodejs and express. The problem occurs when i try to use GET with parameters.
This is my routes code
router.get('/addFriends/:email', (req, res, next) =>{
const email = req.params.email;
UserSchema.find({email: email}, { "friendsPending.emailSender": 1, _id : 0}, (err, data) =>{
if(err){
res.status(404).send(err);
}else{
res.status(200).send(data[0]);
}
});
});
This is my call in Postman : /users/addFriends?email=a
When running this call, server returns 404 status. It happened even when i tested it with another get call.Any comments are appriciated, however other POST and GET calls work normally (they use body not parameters). Thanks
You mixed query params and url params. To make your example working, you need to use /addFriends/my-email#gmail.com instead of /users/addFriends?email=a.
If you need to send emails via query params (everything after ?) use req.query in your controller instead of req.params.email.
This route definition:
router.get('/addFriends/:email', ...);
expects a URL that looks like this:
/addFriends/someEmail
And, you would use req.params.email to refer to the "someEmail" value in the URL path.
Not what you are trying to use:
/addFriends?email=a
If you want to use a URL such as (a URL with a query parameter):
/addFriends?email=a
Then, you would have a route definition like this:
router.get('/addFriends', ...);
And, then you would refer to req.query.email in the route handler. Query parameters (things after the ? in the URL) come from the req.query object.
In Express, route definitions match the path of the URL, not the query parameters.
when you use /addFriends/:param you force the router to match any request tha have a part in path as :param.For example:
/users/addFriends/toFavorates // will **match**
/users/addFriends/toFavorates?email=a // will **match**
/users/addFriends?email=a // will **not** match
if you want to make :param as optional part of url path put a ? after it
/addFriends/:param?
it will tell express route that :param is an optinal part. See this question
express uses path-to-regexp for matching the route paths. read the documentation for more options

node.js request post retrieve last id from db.json

After posting in db.json a new record (transaction with several data), I would like to get the id of the new record before going on. How-to do it ? I am stuck
I have in my db.json a "table" positions with an id automatically generated
my request is
request({
url: url + '/api/positions,
method: 'POST',
form: transaction
}, ????);
I want in my callback retrieve position.id (as I have to use it in another part of code).
Thanks a lot
Olivier
Make sure your API is giving back the position id, Im assuming you're using express, so in /api/positions have the response be res.send({position...});
EDIT, So you're asking about routing? Here is an awesome guide: https://expressjs.com/en/guide/routing.html but Ill give you an example of what I mean.
app.post('/api/positions', function(req, res) {
//your logic goes here, so you are sending a 'transaction' object
// npm install and use body parser so you can retrieve attributes
// from the body of the post
res.send({position: x})
})
Maybe some thing like that.
...
var router = jsonServer.router('db.json');
...
// 'router.db.get' will fetch any first level attribute from your db.json
var positions = router.db.get('positions').value();
var lastPosition = positions[positions.length-1];

Array as parameter in GET request in Postman

I have to send array of ids in GET request as paramenter.How can I test it in Postman(google chrome extension for API testing)?
The scenario is I have url, www.something.com/activity/poi_ids
poi_ids should conatain arrays of ids like [316,318]
At api side using express,
app.get('/activity/:poi_ids',function(req,res){
var poi_ids = req.params.poi_ids;
.......
.......
});
I have looked into it but it is only for post request
you can send them via query params ..
in your http query params assign all values to same variables like
GET activity?pid=12&pid=23&pid=34
and then inside your express get it like
var ids=req.query.pid; //[12,23,34]
It is unstructured text. If you want to "send an array" then you'll need to design some way to encode it and then write JavaScript to decode it.
For example:
GET /activity/316-318
and
var poi_ids = req.params.poi_ids.split("-");

Resources