How does Query.prototype.Symbol.asyncIterator() works in Mongoose ?
The Query.prototype.Symbol.asyncIterator() function is used to return an asyncIterator for use with for/await/of loops. And it works for find() queries. User does not need to call this function explicitly, it gets automatically called by the JavaScript runtime.
Syntax:
Query.prototype.Symbol.asyncIterator()
Parameters: This function does not have any parameter.
Return Value: This function Returns an asyncIterator for use with for/await/of loops.
Installing mongoose :
npm install mongoose
After installing the mongoose module, you can check your mongoose version in command prompt using the command.
npm mongoose --version
Database: The sample database used here is shown below.
After that, you can just create a folder and add a file for example, index.js as shown below.
Project Structure: The project structure will look like this.
Example 1:
index.js
const mongoose = require( 'mongoose' ); // Database connection useNewUrlParser: true , useCreateIndex: true , useUnifiedTopology: true }); // User model const User = mongoose.model( 'User' , { name: { type: String }, age: { type: Number } }); const Query = User.find(); console.log( "Value: " , Query.asyncIterator) |
Run index.js file using below command:
node index.js
Output:
Value: undefined
Note: If Symbol.asyncIterator is undefined, that means your Node.js version does not support async iterators.
Example 2:
index.js
const express = require( 'express' ); const mongoose = require( 'mongoose' ); const app = express() // Database connection useNewUrlParser: true , useCreateIndex: true , useUnifiedTopology: true }); // User model const User = mongoose.model( 'User' , { name: { type: String }, age: { type: Number } }); const Query = User.find(); console.log( "Using Express: " , Query.asyncIterator) app.listen(3000, function (error ){ if (error) console.log(error) console.log( "Server listening on PORT 3000" ) }) |
Run index.js file using below command:
node index.js
Output:
Using Express: undefined
Reference:
https://mongoosejs.com/docs/api/query.html#query_Query-Symbol.asyncIterator
Please Login to comment...