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.