首页 > 解决方案 > MongoDB插入一个缓冲区10000错误无法将数据保存在数据库中

问题描述

我已经检查了所有这些东西:-

现在我仍然收到错误

Mongo连接代码

  const connectDB = async() =>{
    await mongoose.createConnection(URI, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        useCreateIndex: true,   })   
 .then(() => console.log("Database connected!"))
 .catch(err => console.log(err));
    }

发布请求

connectDB();

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');


app.use(cor());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// app.use('/', indexRouter);
// app.use('/users', usersRouter);

app.post('/shorturl',async (req,res)=>{
  let shortUrl = new shorturl({full:req.body.fullurl})
  console.log("Saving!!")
   await shortUrl.save()
    
   .then(()=>{ console.log("Inserted!!"); res.send(shortUrl.short)}).catch(error => console.log("ERROR"));
  //await shorturl.create({full:req.body.fullurl}) 
  //  if(shortUrl == null )return res.sendStatus(404);
    
})

得到

它发出一个 get req 但没有返回任何东西。甚至没有任何错误,它只是一次又一次地发出 get req。

app.get('/:shortUrl',async (req,res)=>{
   try{ 
    const shortUrl = await shorturl.findOne({ short: req.params.shortUrl })
   .then(()=>{
      if(shortUrl == null) return res.sendStatus(404);
      res.redirect(shortUrl.full);
   })
  }
  catch{(error)=> console.log(error)};
})

标签: node.jsmongodbexpress

解决方案


一般只有一个连接时使用mongoose.connect(),而如果有多个连接实例,则使用mongoose.createConnection()

在您的情况下,我看到您使用过createConnection(). 因此,您不能通过 直接访问您的模型mongoose.model,因为它们是“在”不同的连接中定义的。

如果您想继续createConnection(),请参阅此答案

否则,您可以简单地使用mongoose.connect()

前任:

const mongoose = require("mongoose");

//do not use .then() with async/await. use a try/catch block to catch errors
const connectDB = async() =>{
      try {
        const conn = await mongoose.connect(URI, {
            useNewUrlParser: true,
            useUnifiedTopology: true,
            useCreateIndex: true,   });
        console.log("Database connected!"));
        return conn;  
      } catch (error) {
          //handle error
          console.error(error);
          return error;
      }
   }

// ideally you should only start the server if the the database connection was successfully established
connectDB().then(() => {
      app.listen(process.env.PORT, () =>
      console.log(`Example app listening on port ${process.env.PORT}!`),
    );
});

PS: 在大多数简单的项目中,您不必担心指定不同的读取或写入设置、池大小、与不同副本服务器的单独连接等,这就是.connect存在的原因。

但是,如果您有更苛刻的要求(例如出于法律或性能原因),您可能必须使用.createConnection.


推荐阅读