Home > Software engineering >  Mongoose method chain order doesn't seem to matter
Mongoose method chain order doesn't seem to matter

Time:01-15

I was using mongoose to query my database when I noticed that the order of methods doesn't really seem to matter. Why is this?

find({}, { __v: 0, _id: 0 })
.skip(skip)
.limit(limit)
.sort("age")

how does the above query result in the same data as the following:

find({}, { __v: 0, _id: 0 })
.sort("age")
.skip(skip)
.limit(limit)

CodePudding user response:

In Mongoose Model.find initializes and returns a Query object. It does not send anything to the database server, and does not execute any data operation.

The query object has methods sort, skip, limit. Each of these will modify the query, and return the modified object.

The query is executed when the promise is awaited, or the exec method is called.

Essentially, find and the query methods build a find database command that is submitted to the mongodb server all at once.

Both of the sample snippets will produce the same database command to be sent:

{
  find: "collectionname",
  filter: {},
  sort: {"age": 1},
  projection: { __v: 0, _id: 0},
  skip: skip,
  limit: limit
}

The mongodb server will sort the results first, then skip, then limit. If you need the processed in a different order, consider using aggregation

  • Related