MaxRocket
MaxRocket

Reputation: 992

MongoDB Node Express GET and DELETE work, not POST?

GET works. DELETE works.

Can't figure out why POST won't work with something as simple as.

{"akey":"avalue"}

Using Postman to test. The error from Postman is "Could not get any response," which is weird, because I have no problems with GET and DELETE.

New to Mongo/Node. Following Brad Traversy's https://www.youtube.com/watch?v=j55fHUJqtyw tutorial on Vue, Mongo, Express, Node.

Anything stand out?

const express = require( 'express' );
const mongodb = require( 'mongodb' );

const router = express.Router();

// GET POSTS
router.get( '/', async ( req, res ) => {
    const posts = await loadPostsCollection();
    res.send( await posts.find( {} ).toArray() );
} );

// ADD POST
router.post( '/', async ( req, res ) => {
    const posts = await loadPostsCollection();
    await posts.insertOne( {
                               text: req.body.text
                           } );
    res.status(201).send();
} );

// DEL POST
router.delete('/:id', async (req, res)=>{
    const posts = await loadPostsCollection();
        await posts.deleteOne({_id: new mongodb.ObjectID(req.params.id)});
        res.status(200).send();
})

async function loadPostsCollection() {
    const client = await mongodb.MongoClient.connect( 'mongodb+srv://someUser:[email protected]/test?retryWrites=true&w=majority', {
        useNewUrlParser   : true,
        useUnifiedTopology: true
    } );
    return client.db( 'someDB' ).collection( 'somCollection' )
}

module.exports = router;

Upvotes: 0

Views: 449

Answers (2)

Lazer Porter
Lazer Porter

Reputation: 334

If you can put some logic to handle errors there may be useful information there.

// ADD POST
router.post( '/', async ( req, res ) => {
    const posts = await loadPostsCollection();
    await posts.insertOne( {
                           text: req.body.text
                       })
    .then(result => if (result) res.status(201).send());  // handle success case
    .catch(err => { //see what the error is
        console.error; 
        res.status(500)
        res.render('error', { error: err })
        })
});

Upvotes: 1

Yooooomi
Yooooomi

Reputation: 985

Reason

It seems like your await posts.insertOne({ text: req.body.text }); never ends (or crashes and express doesn't respond), so Postman never gets the response.

Try console.loging after your await to see if it's the root cause of the problem.

Possible solution

Try something this way to handle errors about your db requests

router.post('/', async (req, res) => {
  try {
    const posts = await loadPostsCollection();
    await posts.insertOne({
      text: req.body.text
    });
    res.status(201).send(); // You may need to answer something here
  } catch (e) {
    console.error(e);
    return res.status(500).end() // 500 is INTERNAL SERVER ERROR
  }
});

Upvotes: 2

Related Questions