gpt4 book ai didi

node.js - 如何解决 Mongoose 中的 UnhandledPromiseRejectionWarning?

转载 作者:IT老高 更新时间:2023-10-28 12:31:21 26 4
gpt4 key购买 nike

我正在尝试使用 mongoose 获取数据。

所以每次我从 api 获取帖子时——localhost:3000/api/posts——我都会收到我无法解密的 foll 错误。

(node:12100) UnhandledPromiseRejectionWarning: Unhandled promise rejection (r
ejection id: 1): [MongoError: connect ETIMEDOUT xxxx]

下面是我在 api.js 文件中的代码。如果您能提供有关我在哪里出错的指导,我将不胜感激。

const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const post = require('../models/post');

const db = "mongodb://<dbuser>:<dbpassword>@xxxxxxx.mlab.com:xxxxxx/xxxxxx";

mongoose.Promise = global.Promise;
mongoose.connect(db, function(err) {
if(err) {
console.log('Connection error');
}
});

router.get('/posts', function(req, res) {
console.log('Requesting posts');
post.find({})
.exec(function(err, posts) {
if (err) {
console.log('Error getting the posts');
} else {
res.json(posts);
console.log(posts);
}
});
});
//in order for server.js file to access the api, we have to add the foll line
module.exports = router;

2017 年 5 月 23 日

现在我也收到了弃用警告,而事实上我已经包含了 foll loc:

mongoose.Promise = global.Promise; //we add this because if we dont, you may get a warning that mongoose's default promise library is deprecated

如果我能就这个问题获得一些指导,我将不胜感激。谢谢

最佳答案

添加我的答案,因为其他人没有给出清晰的画面。

由于您将 mongoose 用作全局 promise mongoose.Promise = global.Promise 您必须使用 .then( ).catch()

方法如下:

...
mongoose.Promise = global.Promise;
mongoose.connect(db)
.then(res => console.log("Connected to DB"))
.catch(err => console.log(err))
...

关于node.js - 如何解决 Mongoose 中的 UnhandledPromiseRejectionWarning?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44107128/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com