问题描述
我正试图使用猫鼬来获取数据.
I'm trying to fetch data using mongoose.
所以每次我要从api中获取帖子时-localhost:3000/api/posts-我会收到无法解密的foll错误.
So everytime i got to fetch the posts from the api -- localhost:3000/api/posts -- i get the foll error that i am unable to decypher.
foll是我在api.js文件中的代码.如果您能提供有关我在哪里出错的指南,我们将不胜感激.
The foll is my code in the api.js file. I'd appreciate if you can provide guidance on where i am going wrong with this.
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日
May 23, 2017
现在,当我实际上包含了foll loc时,我也会收到弃用警告:
Now i'm also getting deprecation warning when in fact i have included the 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
如果能就此问题获得一些指导,我将不胜感激.谢谢
I'd appreciate if i can get some guidance with this issue. Thanks
推荐答案
您需要为代码提供一些拒绝处理程序,例如:
You need some reject handler for your code, for example:
router.get('/posts', function(req, res) {
console.log('Requesting posts');
post.find({})
.exec()
.then(function(posts) {
res.json(posts);
console.log(posts);
})
.catch(function(error){
console.log('Error getting the posts');
});
});
或者不使用promise链接,而只使用回调函数:
Or don't use promise chaining use just callback function:
router.get('/posts', function(req, res) {
console.log('Requesting posts');
post.find({}, function(err, posts){
if (err) {
console.log('Error getting the posts');
} else {
res.json(posts);
console.log(posts);
}
})
});
这篇关于如何解决猫鼬中的UnhandledPromiseRejectionWarning?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!