0
0
MongodbHow-ToBeginner · 3 min read

How to Create a Document Using Mongoose in MongoDB

To create a document using mongoose, first define a Schema and Model. Then, create an instance of the model with your data and call save() to store it in the database.
📐

Syntax

Creating a document in Mongoose involves these steps:

  • Define a Schema: This sets the structure of your data.
  • Create a Model: This is a class based on the schema to create documents.
  • Create a Document: Instantiate the model with data.
  • Save the Document: Use save() to store it in MongoDB.
javascript
const mongoose = require('mongoose');

// Define schema
const schema = new mongoose.Schema({
  fieldName: String
});

// Create model
const Model = mongoose.model('ModelName', schema);

// Create document
const doc = new Model({ fieldName: 'value' });

// Save document
await doc.save();
💻

Example

This example shows how to create and save a user document with a name and age.

javascript
const mongoose = require('mongoose');

async function run() {
  await mongoose.connect('mongodb://localhost:27017/testdb');

  const userSchema = new mongoose.Schema({
    name: String,
    age: Number
  });

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

  const user = new User({ name: 'Alice', age: 25 });

  const savedUser = await user.save();
  console.log('Saved user:', savedUser);

  await mongoose.disconnect();
}

run().catch(console.error);
Output
Saved user: { _id: <ObjectId>, name: 'Alice', age: 25, __v: 0 }
⚠️

Common Pitfalls

Common mistakes when creating documents with Mongoose include:

  • Not connecting to MongoDB before saving documents.
  • Forgetting to await the save() call, causing unexpected behavior.
  • Using incorrect schema types or missing required fields.
  • Trying to create documents without defining a model first.
javascript
/* Wrong: Not awaiting save() */
const user = new User({ name: 'Bob' });
user.save(); // This may cause issues because it's async

/* Right: Await save() */
await user.save();
📊

Quick Reference

Remember these quick tips when creating documents with Mongoose:

  • Always define a schema before creating a model.
  • Use new Model(data) to create a document.
  • Call await doc.save() to save the document.
  • Ensure MongoDB connection is open before saving.

Key Takeaways

Define a schema and model before creating documents in Mongoose.
Create a document by instantiating the model with your data.
Always await the save() method to ensure the document is stored.
Connect to MongoDB before attempting to save documents.
Check schema types and required fields to avoid errors.