Home > Blockchain >  how to get records from mongodb through node js
how to get records from mongodb through node js

Time:07-03

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

CodePudding user response:

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