Introduction to Mongoose Documents

Mongoose documents represent a one-to-one mapping to documents stored in a MongoDB collection. Every document is an instance of its model.

Documents vs. models

In Mongoose, both Document and Model are two separate classes. The Model class is a subclass of the Document class. When you call the Model class constructor, you actually create a new document:

const mongoose = require('mongoose')
const { Schema } = mongoose

const Product = mongoose.model(
  'Product',
  new Schema({
    name: String,
    price: Number
  })
)

const prod = new Product()

prod instanceof mongoose.Model // true
prod instanceof mongoose.Document // true

Querying documents

You can retrieve a Mongoose document from the MongoDB using model functions like findOne():

const product = await Product.findOne({ name: 'Pizza' })

To retrieve multiple documents, use the find() method instead:

const products = await Product.find({ price: { $gt: 10 } })

Updating documents

All the changes made to a Mongoose document are tracked. You can modify a document just like a JavaScript object, and Mongoose will automatically convert it into a MongoDB update query:

const pizza = await Product.findOne({ name: 'Pizza' })
pizza.price = 10

await pizza.save()

To update more than one document at once, you should use the updateMany() function:

await Product.updateMany({ price: { $lte: 5 } }, { $set: { price: 10 } })

Deleting documents

Mongoose models have static deleteOne() and deleteMany() functions for removing all documents matching the given filters:

// Delete one document
await Product.deleteOne({ name: 'Pizza' })

// Delete multiple documents
await Product.deleteMany({ price: { $lt: 5 } })

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.