mongodb Mongoose 错误:10000ms后,操作“.insertOne()"缓冲超时

axkjgtzd  于 2022-12-18  发布在  Go
关注(0)|答案(2)|浏览(214)

作为sith express和MongoDB的入门项目,我正在创建一个简单的API,它将返回一个笑话,为此,我正在创建一种方法,让用户发送一个POST请求,在请求体中包含笑话类型和笑话,这将把笑话添加到我的集群中。
我正在使用以下架构:

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)

使用以下请求后代码:

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
    }

})

使用失眠发送post请求时,我在控制台中收到以下错误

D:\api\jokesAPIV2\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:158
          const err = new MongooseError(message);
                      ^

MongooseError: Operation `jokes.insertOne()` buffering timed out after 10000ms
    at Timeout.<anonymous> (D:\api\jokesAPIV2\node_modules\mongoose\lib\drivers\node-MongoDB-native\collection.js:158:23)
    at listOnTimeout (node:internal/timers:559:17)
    at processTimers (node:internal/timers:502:7)


有人知道为什么会这样吗?我该怎么解决?
我几乎尝试了this答案中建议的所有方法。

yshpjwxd

yshpjwxd1#

create返回一个Promise。另外,请确保正确地对req.body进行反结构:

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 });
  }
});
5lhxktic

5lhxktic2#

你不需要JokeSchema.save;部分,因为.create()方法会做所有的事情。但是,你必须在.create()方法之前添加await,并指定函数为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.' });
  }
})

相关问题