javascriptnode.jsmongodbcallbackmongodb-nodejs-driver

How would I know if "err" argument is needed in the callback?


I am a beginner in mongodb and javascript.

I have here a code for simple find method in Mongodb Nodejs. This code does not work.

The solution is to change the last line to this: cursor.limit(10).toArray((err, docs) => console.log(docs));.

What I do not understand is why do I need to include the err argument here? Here is the documentation for toArray method. It does not say here that err parameter is needed. How would I know that err argument is needed here or in other methods?

Thank you very much! I think this is a very basic concept and I will appreciate any input.

const client = new MongoClient(uri);
client.connect()
.then(() => {
  const db = client.db('sample_mflix');
  const coll = db.collection('movies');

  const cursor = coll.find();
  cursor.limit(10).toArray((docs) => console.log(docs));

})


Solution

  • In the documentation you linked, we can see that FindCursor.toArray has two valid syntax permutations:

    1. toArray(): Promise<TSchema[]>
    2. toArray(callback: Callback<TSchema[]>): void

    Since you are using the second, we need to look at the documentation for Callback. It says there is only one valid syntax:

    1. Callback<T>: (error?: AnyError, result?: T) => void

    You must include the error parameter to have a valid Callback, then, and you must have a valid Callback to use the toArray(:Callback) permutation.


    The typical way to convey that you don't care about the value of a parameter is to use an underscore (_) as the parameter name.

    const client = new MongoClient(uri);
    client.connect()
        .then(() => {
            const db = client.db('sample_mflix');
            const coll = db.collection('movies');
    
            const cursor = coll.find();
            cursor.limit(10).toArray((_, docs) => { console.log(docs); });
    })
    

    If you wanted to use the first permutation (which returns a Promise), it would look like the following. This is how you're already handling MongoClient.connect.

    const client = new MongoClient(uri);
    client.connect()
        .then(() => {
            const db = client.db('sample_mflix');
            const coll = db.collection('movies');
    
            const cursor = coll.find();
            cursor.limit(10).toArray()
                .then(docs => { console.log(docs); });
    })