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

标签 node.js mongodb mongoose

我正在尝试使用 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/

相关文章:

javascript - 将命令行输入转换为 Node Fluent ffmpeg

node.js - 删除当前发出事件的事件监听器

javascript - 如何从 MD5 哈希生成(1-100)之间的随机数

mongodb - 在 mongodb shell 中打印文档值

javascript - 如何将带有 "$"字段的 JSON 对象插入 Meteor 集合中?

node.js - MongoDB/Mongoose 索引使查询更快还是变慢?

node.js - npm run "script"不执行任何操作

MongoDB:使用精益聚合函数

node.js - 更新命令 mongoskin 后的对象 ID

node.js - 在 mongoose .d.ts 中分配自定义方法,这样我就可以在 typescript 中使用 mongoose 的任何地方使用它们