提问者:小点点

POST后Express js MongoDB返回对象


如何在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());

共2个答案

匿名用户

在mongoDBinsertOne中,方法返回一个文档,其中包含确认的true,当前插入的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);

匿名用户

好的,你可以这样试试

    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)}