简体   繁体   English

如何使用NodeJ在JSON对象中获取响应

[英]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. 我将NodeJs和MongoDb用作后端服务。我的集合中有几个文档,其字段名为_id和Name。

I want to get Output in Json objects like below: 我想在Json对象中获得Output,如下所示:

[ 
  {   
    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 谢谢

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. 相反,您想每次使用属性名称创建一个新对象并返回该数组。

Instead of this 代替这个

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

Use this code 使用此代码

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

I tested the code you provided. 我测试了您提供的代码。 With the collection structure and the query if you remove the line output = result.map(r => r.Name); 使用集合结构和查询(如果要删除), output = result.map(r => r.Name); and just return result you will get the structure: 并返回result您将得到以下结构:

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

Then the code inside the else block would look like this: 然后, else块中的代码将如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM