How to Find All Documents in Mongoose

Jun 24, 2019

Suppose you have a Mongoose model User that contains all your app's users. To get a list of all users in the collection, call User.find() with an empty object as the first parameter:

const User = mongoose.model('User', Schema({
  name: String,
  email: String
}));

// Empty `filter` means "match all documents"
const filter = {};
const all = await User.find(filter);

Equivalently, you can call User.find() with no arguments and get the same result.

await User.find();

Cursors

Suppose your app is very popular and you have millions of users. Loading all your users into memory at once just won't work. To loop through all users one at a time without loading them all into memory at once, use a cursor.

const User = mongoose.model('User', Schema({
  name: String,
  email: String
}));

// Note no `await` here
const cursor = User.find().cursor();

for (let doc = await cursor.next(); doc != null; doc = await cursor.next()) {
  // Use `doc`
}

Alternatively, you can use async iterators.

for await (const doc of User.find()) {
  // use `doc`
}

More Mongoose Tutorials