我試圖抓住用戶的高分帖子。爲此,我查詢Post
模型,在帖子中查找以user._id
作爲author
的帖子。爲什麼不選擇(貓鼬查詢)工作?
這工作得很好。
但是,我只想抓住帖子的_id
和voteCount
。出於某種原因,加上select
只是拋出了錯誤,並說,這是一個unprocessable entity
下面是該查詢:
getHighscorePost(req, res, next) {
const firebaseUID = req.params.uid;
User.findOne({ firebaseUID })
.select('_id')
.then(user => {
Post.find({ author: user._id })
.select('_id, voteCount')
.sort({ voteCount: -1 })
.limit(1)
.then(post => res.send(post[0]))
.catch(next);
})
.catch(next);
}
我試圖把select
前/每個limit
和sort
選項之後。
如果我省略了select
,那麼後控制檯就可以很好地記錄下來;
{ _id: '589ddffeb4a1477fa04d632a',
author: '589ddffeb4a1477fa04d6326',
text: 'This is post two. It belongs to Matt too',
createdAt: 2,
expiresAt: 1000000000000000000,
university: 'University of Aberdeen',
voteCount: 3,
uniOnly: false,
__v: 0,
categories: [ 'music' ],
votes: [],
commenters: [],
comments: [],
expired: false,
commentCount: 0,
id: '589ddffeb4a1477fa04d632a' }
隨着select
的加入,我在身體裏什麼也沒得到。錯誤返回爲:
{ error: 'Cannot read property \'length\' of undefined' }
這裏發生了什麼?
謝謝
一些評論:你只需要外層的'.catch(next)',它也會捕獲內部承諾中的錯誤。你也應該返回'Post.find'。在'.then()'之前嘗試在查詢中添加'.exec()'。 – ChemicalRocketeer