I have a collection and I want to return documents which their views + likes are greater than 100.
How can I do that using mongoose methods?
I have a collection and I want to return documents which their views +
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
That’s not a standard query that you can look up in mongodb without a map-reduce over your full collection.
Here is a tutorial on how to do map-reduce queries with mongoose (looks like it actually uses the underlying node-mongodb-native driver): http://wmilesn.com/2011/07/code/how-to-map-reduce-with-mongoose-mongodb-express-node-js/
Mongoose has a trick up it’s sleeve that can help you in this case, though. Simply create a middleware that updates a field with the combined score on each
save()orupdate()operation. One advantage of this approach is that you can create an index on this combined field and have super fast lookups – much much faster than a map-reduce.This middleware page, or plugin page shows
schema.pre('save', ...)which you can use to automatically update thetotalsfield, each time you save the doc. You can then do a normal query on the totals field > 100.