Digvijay
Digvijay

Reputation: 3281

How to get response in json object using NodeJs

I am using NodeJs and MongoDb as a back-end service.I have several documents in my collection having field named _id and Name.

I want to get Output in Json objects like below:

[ 
  {   
    Name:"Paul"
  },
  {   
    Name:"Jon"
  }
] 

Here is my code:

var express = require('express');    
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
var bodyParser = require('body-parser');

var app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true})); 

app.post('/offers',(req, res) => {

MongoClient.connect(url, (err, db) => {           
if(err) throw err;
var dbo = db.db('Tiffino_db');

dbo.collection("Offers")
    .find({},{ projection: { _id: 0 } })
    .toArray((err, result) => {
         if (err) {
                 console.log("Error:", +err);
             }
             else { 
                 output =  result.map(r => r.Name);
                 res.json({"Name":output});
                 db.close();
            }
       });
   });
});

Here is my Output:

{
"Name": [
    "Paul",
    "Jon",
    "David",
    "Aina"
  ]
}

Please let me know how to modify code to get desired output.

THANKS

Upvotes: 0

Views: 143

Answers (3)

ddsultan
ddsultan

Reputation: 2307

I tested the code you provided. With the collection structure and the query if you remove the line output = result.map(r => r.Name); and just return result you will get the structure:

[{ "Name": "TestName" }, { "Name": "TestNam2" }]

Then the code inside the else block would look like this:

res.json(result);
db.close();

Upvotes: 0

Osama
Osama

Reputation: 3030

Instead of this

res.json({"Name":output})

Use this code

var json=    output.map(element=>{
    return {"Name":element.Name};
});

Upvotes: 2

Shilly
Shilly

Reputation: 8589

Instead of:

output = result.map(r => r.Name); res.json({"Name":output});

Try:

output = result.map( r => ({ "Name": r.Name })); res.json( output );

As written, you map all the resulting records into one array, then assign that array to the property name. Instead you want to create a new object with the property name every time and return that array.

Upvotes: 1

Related Questions