node.js - MongoDB插入一个缓冲区10000错误无法将数据保存在数据库中
问题描述
我已经检查了所有这些东西:-
- ip白名单
- 异步函数尝试捕获
- 户口密码
- 节点版本
现在我仍然收到错误
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)};
})
解决方案
一般只有一个连接时使用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
.
推荐阅读
- android - Android 模拟器中的布局看起来与布局编辑器上显示的不同
- flutter - Flutter 2.0.0 Link Widget 使用方法?
- python - 如何创建n个变量的函数(python)
- mongodb - 获取所有文档,其中 diff beetwen 当前时间戳和一些具有纳秒值的列的值更多一些间隔
- android - 如何更改材质 TabItem 中的图标大小?
- ios - swift - iOS 如何防止 ios 自定义导航栏在键盘出现时向上移动
- http - 找不到与具有绑定 BasicHttpBinding 的端点的方案 https 匹配的基地址。注册的基地址方案是 [http]
- here-api - 使用 HERE Rest API 的最佳实践 - 直接通过客户端或通过我的后端服务器
- r - 基于 P 值显示回归线
- python - Pandas:基于条件的列的唯一值