0
0
MongodbHow-ToBeginner · 3 min read

How to Use Default Values in Mongoose Schema

In Mongoose, you set a default value for a schema field by adding the default property in the schema definition. This value is used automatically when a new document is created without specifying that field.
📐

Syntax

Use the default property inside the schema field definition to specify a value that Mongoose will use if no value is provided.

  • fieldName: { type: DataType, default: defaultValue }
  • defaultValue can be a static value or a function returning a value.
javascript
const schema = new mongoose.Schema({
  fieldName: { type: String, default: 'default text' },
  createdAt: { type: Date, default: Date.now }
});
💻

Example

This example shows a simple Mongoose schema with default values for status and createdAt. When a new document is saved without these fields, Mongoose fills them automatically.

javascript
const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/testdb', { useNewUrlParser: true, useUnifiedTopology: true });

const userSchema = new mongoose.Schema({
  name: String,
  status: { type: String, default: 'active' },
  createdAt: { type: Date, default: Date.now }
});

const User = mongoose.model('User', userSchema);

async function run() {
  const user = new User({ name: 'Alice' });
  await user.save();
  console.log(user);
  mongoose.connection.close();
}

run();
Output
{ _id: ObjectId("..."), name: 'Alice', status: 'active', createdAt: 2024-06-01T12:00:00.000Z, __v: 0 }
⚠️

Common Pitfalls

Common mistakes when using default in Mongoose schemas include:

  • Setting default to a function call instead of a function reference, causing the default to be the same value for all documents.
  • Not specifying the type property, which can lead to unexpected behavior.
  • Expecting default to apply on updates, but it only applies when creating new documents.
javascript
const wrongSchema = new mongoose.Schema({
  date: { type: Date, default: Date.now() } // wrong: calls Date.now immediately
});

const rightSchema = new mongoose.Schema({
  date: { type: Date, default: Date.now } // correct: passes function reference
});
📊

Quick Reference

PropertyDescriptionExample
typeData type of the fieldString, Number, Date, etc.
defaultValue used if none provided'active', Date.now, () => new Date()
function as defaultUse a function to get dynamic defaultdefault: Date.now
static valueUse a fixed value as defaultdefault: 'pending'

Key Takeaways

Use the default property in schema fields to set automatic values when none are provided.
Pass a function reference (e.g., Date.now) for dynamic defaults, not a function call.
Default values apply only when creating new documents, not on updates.
Always specify the type along with default for clarity and correctness.