skip to Main Content

As a getting-started project with express and MongoDB, I am creating a simple API that will return a joke. For that, I am making a way for users to send a POST request with the joke type and joke in the body which will add the joke to my cluster.

I am using the following Schema:

const mongoose = require('mongoose');
const schema = mongoose.Schema;

const jokecreateWay = new schema({

    JokeType: {
        type: String,
        //required: true
    },
    joke: {
        type: String,
        //required: true,
    },

})

module.exports = mongoose.model('joke', jokecreateWay)

with the following post-request code:

app.post('/add-joke', (req, res) => {
    const joke = req.body;
    const gType = req.body;

    const strigifiedJoke = JSON.stringify(joke);
    const strigifiedGType = JSON.stringify(gType);

    if (joke != null || gType != null) {
        try {

            const toBeInserted = JokeSchema.create({
                JokeType: strigifiedGType,
                joke: strigifiedJoke,
            });

            JokeSchema.save;
            return res.status(201).send({ message: 'joke added' });
        }
        catch (err) {
            return res.status(400).send({ message: err });
        }
    }
    else {
        res.status(418).send({ message: "You forgot to either specify the joke or its type." })
        return
    }

})

using insomnia to send the post request I get the following error in the console

D:apijokesAPIV2node_modulesmongooselibdriversnode-mongodb-nativecollection.js:158
          const err = new MongooseError(message);
                      ^

MongooseError: Operation `jokes.insertOne()` buffering timed out after 10000ms
    at Timeout.<anonymous> (D:apijokesAPIV2node_modulesmongooselibdriversnode-MongoDB-nativecollection.js:158:23)
    at listOnTimeout (node:internal/timers:559:17)
    at processTimers (node:internal/timers:502:7)

Does anyone know why this happens and how I can fix it?

I have tried mostly everything suggested in this answer.

2

Answers


  1. create returns a Promise. Also, make sure to destructure the req.body correctly:

    app.post('/add-joke', async (req, res) => {
      try {
        const { joke, gType } = req.body;
    
        if (joke === '' || gType === '') {
          return res.status(418).send({
            message: 'You forgot to either specify the joke or its type.',
          });
        }
    
        const toBeInserted = await JokeSchema.create({
          JokeType: gType,
          joke: joke,
        });
    
        return res.status(201).send({ message: 'joke added' });
      } catch (err) {
        return res.status(400).send({ message: err });
      }
    });
    
    Login or Signup to reply.
  2. You don’t need JokeSchema.save; part since the .create() method will do everything. However, you have to add await before .create() method, and specify the function to be async.

    app.post('/add-joke', async (req, res) => {
      const { joke, gType } = req.body;
    
      // Validations
      if(!joke || !gType) {
        return res.status(400).json({ success: false, message: 'One of the input is missing.' });
      }
    
      try {
        const joke = await JokeSchema.create({ JokeType: gType, joke });
        return res.status(200).send({ success: true, message: 'Joke successfully created.' });
      } catch(error) {
        return res.status(400).json({ success: false, message: 'Error while adding joke.' });
      }
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search