2017-02-10 28 views
1

我試圖抓住用戶的高分帖子。爲此,我查詢Post模型,在帖子中查找以user._id作爲author的帖子。爲什麼不選擇(貓鼬查詢)工作?

這工作得很好。

但是,我只想抓住帖子的_idvoteCount。出於某種原因,加上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前/每個limitsort選項之後。

如果我省略了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' } 

這裏發生了什麼?

謝謝

+0

一些評論:你只需要外層的'.catch(next)',它也會捕獲內部承諾中的錯誤。你也應該返回'Post.find'。在'.then()'之前嘗試在查詢中添加'.exec()'。 – ChemicalRocketeer

回答

2

我認爲你不需要在你的選擇中使用分號。因此,而不是這樣的:

.select('_id, voteCount')

你的選擇應該是這樣的:

.select('_id voteCount')

至少我會這麼說基於docs

+0

仍然沒有工作:( – bloppit

+0

我這樣做,但它只是給了我同樣的錯誤? – bloppit

1

默認情況下應包含_id。你可以試試:

.select('voteCount') 
+0

仍然不工作:( – bloppit

+0

我這樣做,但它只是給了我同樣的錯誤? – bloppit

1

可以使用

Post.find({ author: user._id }, {voteCount: 1}) 

你不需要把_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); 
    } 

希望它應該工作得很好,但無論如何,讓我知道,如果這個工程。

+0

仍然沒有工作:( – bloppit

+0

我這樣做,但它只是給了我同樣的錯誤? – bloppit