【发布时间】:2018-11-09 22:10:18
【问题描述】:
我在这里遇到了这个小问题/困惑...我实际上能够使用findById(req.params.articleId)通过他们的_id 获得一篇单独的文章
我的获取请求
router.get('/:articleId', function (req, res, next) {
var decoded = jwt.decode(req.query.token);
Article.findById(req.params.articleId, 'keyskeys')
.populate('user')
.exec( function (err, article) {
console.log('see out article too', article)
// if the ID is not found or invalid, return err
if (err) {
return res.status(500).json({
title: 'An error occured',
error: err
});
}
// if the article was not found anyways
if (!article) {
return res.status(500).json({
title: 'Article not found',
error: { message: 'Article was not found!' }
});
}
return res.json({
success: true,
message: 'successful :id',
article: article,
});
});
});
Postman 正在返回 200 ok,但返回的数据不只是我想要的
它只是返回 objectID 而我需要它来获取该特定 ID 的整个对象以使用...
我在这里有点困惑,在谷歌上搜索了一下,无法真正掌握一些东西......
邮递员回来了
{
"success": true,
"message": "successful :id",
"article": {
"_id": "5b0af26a0321733524c64c91"
}
}
它应该返回类似的东西
{
"_id" : ObjectId("5b0af26a0321733524c64c91"),
"favoritesCount" : 33,
"title" : "jfdkjkjgfkgfkll",
"description" : "lkfgmfglkgfklgfk",
"body" : "klmfl,,;lvk;lggpog,gf.,gf.gl.",
"username" : "qqqq",
"userId" : ObjectId("5b0af2500321733524c64c90"),
"__v" : 0
}
任何帮助将不胜感激
【问题讨论】:
-
findOne的第二个参数是要包含的字段的名称,您只列出了'keyskeys'。你想用它做什么? -
keyskeys只是一个令牌,我需要通过它才能访问该特定路线... -
不知道为什么你认为你需要在那里传递
keyskeys,但findOne的第二个参数告诉 Mongoose 你想要返回哪些字段,正如 JohnnyHK 所说。由于您的文档中没有任何keyskeys字段,因此仅返回_id。如果你只是完全删除keyskeys参数,你应该得到你想要的输出。 -
感谢@Sven 的提醒...我现在可以看到我的错误了...
标签: javascript node.js mongodb mongoose mean