Search code examples
javascriptmongodbmongoosecursor

Mongoose for/await/of loop is `sort` required in Query?


From documentation of Mongoose there is the following example about iterating with async/await:

// Works without using `cursor()`
for await (const doc of Model.find([{ $sort: { name: 1 } }])) {
  console.log(doc.name);
}

Since I am quite new in MongoDB, I want to understand if [{ $sort: { name: 1 } }] is required to get the query working or it is only an example.

My goal is to iterate all the documents in a Collection, so I suppose that following code should be fine:

// Works without using `cursor()`
for await (const doc of Model.find()) {
  console.log(doc.name);
}

Is it correct?


Solution

  • In Mongodb 4.2 and older passing an array of objects to find will trigger an exception. So if you run:

    Model.find([{ $sort: { name: 1 } }]).then(...)
    

    you will get:

    ObjectParameterError: Parameter "filter" to find() must be an object
    

    However, in MongoDB 4.4, [{ $sort: { name: 1 } }] can, in fact, be passed to find. However, $sort does not actually go into find params, but rather should be used like so Model.find().sort({name: 1}).

    That makes me believe that [{ $sort: { name: 1 } }] in the link you supplied is just a placeholder and servers no purpose. So running

    for await (const doc of Model.find()) {
    

    is perfectly fine.