fhlkm fhlkm - 3 months ago 15x
Node.js Question

What do the find() and sort()mean in Mongoose?

I am new to mongoose, so there are something I don't quite understand.

The code like the below:

The question is

1 I can't find have two parameters here(it is like find({})), why in this code find have two parameters?

2what does "sort(order+sort)" mean ? I am confused.

var sort = req.query.sort || "created";
var order = (req.query.order === "asc" ? "-" : "");
var limit = req.query.limit || "20";
var offset = req.query.offset || "0";

Opportunities.find(filterObject, '-email')
.sort(order + sort)
.exec(function (err, opportunities) {
if (err) return handleError(res, err);
return res.json(200, opportunities);


The second argument to find is the projection of result objects. That is, it is a list of fields you want to include or exclude in each result object found by the query. If you use field names prefaced by minus signs (-foo), then you are signifying that you want all fields except that listed fields. So, the argument -email means, "When showing me results, exclude the email field, but include all other fields".

The sort function can also use field names with or without a minus sign, indicating whether the results should be sorted descending or ascending:

The sort order of each path is ascending unless the path name is prefixed with - which will be treated as descending.

The order variable is either the one-character string - or the empty string, based on the desired direction of the sort. This gets prepended to the field name used to sort the results (i.e., the sort variable).