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`
}

Want to become your team's MongoDB expert? "Mastering Mongoose" distills 8 years of hard-earned lessons building Mongoose apps at scale into 153 pages. That means you can learn what you need to know to build production-ready full-stack apps with Node.js and MongoDB in a few days. Get your copy!

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Mongoose Tutorials