为什么不select(mongoose查询)工作?

我试图抓住一个用户的高分职位。 为此,我查询Post模型,查找以user._id作为post中的author的post。

这工作得很好。

不过,我只想抓住post的_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那么后台控制台就会如此logging;

 { _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分号。 所以,而不是这个:

.select('_id, voteCount')

你的select应该是这样的:

.select('_id voteCount')

至less我会这样说,根据文档 。

_id应该是默认包含的。 你可以试试:

 .select('voteCount') 

您可以使用

 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); } 

希望它应该工作得很好,但无论如何,让我知道这是否工作。