Jan
Jan

Reputation: 663

Express js MongoDB return object after POST

How can I get the object back from the database in Express js? When I do a POST request I only get a status 201 back and not the object from the response.

The way as it is below it returns an empty res.data field instead of the object.

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

To get all the objects back in an array I can do so like this:

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

Upvotes: 1

Views: 1317

Answers (2)

akshay bagade
akshay bagade

Reputation: 1219

ok you can try this way

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

or this way

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

Upvotes: 0

Anwar Hussain
Anwar Hussain

Reputation: 450

In mongoDB insertOne method returns a document containing acknowledged as true and the currently inserted id (ObjectId) as insertedId. So you can store the response from mongoDB in a variable and if there's any insertedId found you can query the data from mongoDB or prepare your data from request body.

...
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);

I hope it works!

Upvotes: 2

Related Questions