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));
})
In the documentation you linked, we can see that
FindCursor.toArrayhas two valid syntax permutations:toArray(): Promise<TSchema[]>toArray(callback: Callback<TSchema[]>): voidSince you are using the second, we need to look at the documentation for
Callback. It says there is only one valid syntax:Callback<T>: (error?: AnyError, result?: T) => voidYou must include the
errorparameter to have a validCallback, then, and you must have a validCallbackto use thetoArray(: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.If you wanted to use the first permutation (which returns a
Promise), it would look like the following. This is how you're already handlingMongoClient.connect.