fix(cursor): Improve cursor usage documentation and refactor getCursor API to support native cursor modifiers

This commit is contained in:
2025-04-24 11:34:49 +00:00
parent e7c0951786
commit 43f9033ccc
5 changed files with 140 additions and 44 deletions

View File

@@ -133,31 +133,34 @@ const user = await User.getInstance({ username: 'myUsername' });
// Fetch multiple users that match criteria
const users = await User.getInstances({ email: 'myEmail@example.com' });
// Using a cursor for large collections
// Obtain a cursor for large result sets
const cursor = await User.getCursor({ active: true });
// Process documents one at a time (memory efficient)
await cursor.forEach(async (user, index) => {
// Process each user with its position
console.log(`Processing user ${index}: ${user.username}`);
// Stream each document efficiently
await cursor.forEach(async (user) => {
console.log(`Processing user: ${user.username}`);
});
// Chain cursor methods like in the MongoDB native driver
const paginatedCursor = await User.getCursor({ active: true })
.limit(10) // Limit results
.skip(20) // Skip first 20 results
.sort({ createdAt: -1 }); // Sort by creation date descending
// Manually iterate using next()
let nextUser;
while ((nextUser = await cursor.next())) {
console.log(`Next user: ${nextUser.username}`);
}
// Convert cursor to array (when you know the result set is small)
const userArray = await paginatedCursor.toArray();
// Convert to array when the result set is small
const userArray = await cursor.toArray();
// Other cursor operations
const nextUser = await cursor.next(); // Get the next document
const hasMoreUsers = await cursor.hasNext(); // Check if more documents exist
const count = await cursor.count(); // Get the count of documents in the cursor
// Always close cursors when done with them
// Close the cursor to free resources
await cursor.close();
// For native cursor modifiers (sort, skip, limit), use getCursor with modifier option:
const paginatedCursor = await User.getCursor(
{ active: true },
{ modifier: (c) => c.sort({ createdAt: -1 }).skip(20).limit(10) }
);
await paginatedCursor.forEach((user) => {
console.log(`Paginated user: ${user.username}`);
});
```
#### Update