无法将json传递给node.js中的rest端点

时间:2017-11-06 14:52:09

标签: javascript node.js mongodb express

如何将json批量插入mongodb?我知道我必须使用insertMany(我正在使用mongoose)但现在我仍然坚持要获得正确的res.body。我的帖子里有这个。

enter image description here

这是我的node.js代码

router.post('/', (req, res) => {    
    console.log(req.body.songs) // ['akon','im lonely','lady gaga','bad romance']    
}

为什么它变成了阵列?在路线之前我有这样的事情:

// Set body parser middleware
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

2 个答案:

答案 0 :(得分:0)

对于像这样的情况,使用JSON通常更容易。在测试时设置这样的邮差:

enter image description here

复制/ pasteable:

{
    "songs": [
        { "artist": "Xzibit", "title": "X" },
        { "artist": "Lady Gaga", "title": "Million Reasons" },
        { "artist": "Adele", "title": "Hello" }
    ]
}

然后创建这样的歌曲:

Songs
  .create(req.body.songs, (err, songs) => {
    let response = {};

    if (err) {
      // handle error
    } else {
      response.status = HttpStatus.CREATED;
      response.message = songs;
    }

    return res.status(response.status).json(response.message);
  });

Create需要创建一个对象数组。

答案 1 :(得分:0)

尝试像这样命名你的密钥

songs[0][artist]

而不是

songs[0].artist