【问题标题】:Express js MongoDB return object after POSTPOST后Express js MongoDB返回对象
【发布时间】:2019-08-08 19:18:10
【问题描述】:

如何在 Express js 中从数据库中取回对象?当我发出 POST 请求时,我只得到状态 201 而不是响应中的对象。

它下面的方式返回一个空的 res.data 字段而不是对象。

router.post('/', async (req, res) => {
  const websites = await loadWebsitesCollection();
  await websites.insertOne({
    title: req.body.title,
    url: req.body.url,
    cms: req.body.cms,
    fw: req.body.fw,
    user: req.body.user,
    createdAt: new Date()
  });
  //TODO Need to get the response from the post request
  res.status(201).send();
  res.status(404).send('Sorry, we cannot find that!');
  res.status(500).send({ error: 'something blew up' });
})

要将所有对象返回到数组中,我可以这样做:

res.send(await websites.find({}).toArray());

【问题讨论】:

标签: javascript mongodb express crud


【解决方案1】:

在 mongoDB 中,insertOne 方法返回一个包含 acknowledgedtrue 和当前插入的 id (ObjectId) 为 insertedId 的文档。因此,您可以将来自 mongoDB 的响应存储在变量中,如果找到任何 insertedId,您可以从 mongoDB 查询数据或从请求正文中准备数据。

...
const insertion = await websites.insertOne({
  title: req.body.title,
  url: req.body.url,
  cms: req.body.cms,
  fw: req.body.fw,
  user: req.body.user,
  createdAt: new Date()
});
let data = {};
if (insertion.acknowledged) {
  // ... prepare the data
  data = await websites.findOne({_id: insertion.insertedId});
}

... 

res.send(data);

我希望它有效!

【讨论】:

  • 一百万谢谢 :)
【解决方案2】:

好的,你可以试试这个方法

    try{let websites = await loadWebsitesCollection.insertOne({
title: req.body.title,
url: req.body.url,
cms: req.body.cms,
fw: req.body.fw,
user: req.body.user,
createdAt: new Date() });;
res.send(websites );}catch(e){res.status(400).send(e)}

或者这样

        try{var websites = new loadWebsitesCollection({
title: req.body.title,
url: req.body.url,
cms: req.body.cms,
fw: req.body.fw,
user: req.body.user,
createdAt: new Date()})var reswebsites  = await websites .insertOne(); res.send(reswebsites );}catch(e){res.status(400).send(e)}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-13
    • 2021-05-17
    • 1970-01-01
    • 2017-08-30
    • 2020-12-16
    • 1970-01-01
    • 2018-04-22
    相关资源
    最近更新 更多