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
create
returns aPromise
. Also, make sure to destructure thereq.body
correctly: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.