[英]Why isn't select (mongoose query) working?
我正在嘗試獲取用戶的高分帖子。 為此,我查詢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' }
這里發生了什么事?
謝謝
我認為您的選擇中不需要分號。 所以而不是這個:
.select('_id, voteCount')
您的選擇應如下所示:
.select('_id voteCount')
至少我會根據docs這么說。
默認情況下應包含_id
。 你可以試試:
.select('voteCount')
您可以使用
Post.find({ author: user._id }, {voteCount: 1})
您不需要 put _id = 1,因為它默認會在輸出中,但如果您不想在輸出中使用 _id,則應該放置 _id=0。
這是完整的代碼:
getHighscorePost(req, res, next) {
const firebaseUID = req.params.uid;
User.findOne({ firebaseUID })
.select('_id')
.then(user => {
Post.find({ author: user._id }, {voteCount: 1})
.sort({ voteCount: -1 })
.limit(1)
.then(post => res.send(post[0]))
.catch(next);
})
.catch(next);
}
希望它應該可以正常工作,但無論如何,讓我知道這是否有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.