Reputation: 641
I'm attempting to grab a User's highscore post. To do this, I query the Post
model, finding posts with their user._id
as the author
in the post.
This is working just fine.
However, I only want to grab the _id
and the voteCount
of the post. For some reason adding a select
just throws up errors and says that it's an unprocessable entity
Here is the query:
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);
}
I've tried putting the select
before/after each of the limit
and sort
options.
If I omit the select
then the post console logs just fine like this;
{ _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' }
With the select
added, I get nothing in the body. The error comes back as:
{ error: 'Cannot read property \'length\' of undefined' }
What's happening here?
Thank you
Upvotes: 1
Views: 159
Reputation: 179
you can use
Post.find({ author: user._id }, {voteCount: 1})
you don't need put _id = 1 as it will be in the output by default, but in case if you don't want _id in your output, you should put _id=0.
Here is the complete code:
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);
}
Hopefully it should work just fine but anyhow, let me know if this works.
Upvotes: 1
Reputation: 111268
The _id
should be included by default. You can try:
.select('voteCount')
Upvotes: 1
Reputation: 5708
I think that you don't need semicolon in your select. So instead of this:
.select('_id, voteCount')
your select should look like this:
.select('_id voteCount')
At least I would say so based on docs.
Upvotes: 2