MongoDB

MongoDB Insert Document Tutorial with JavaScript and Mongoose

See how to insert documents into MongoDB with JavaScript and Mongoose, from a first insertOne() call to practical examples you can reuse.

Serhat ALPASLAN2 min read

MongoDB Data Insertion ,

It is one of the NoSQL database systems and lets you store data as key/value pairs, documents, graphs, or collections. In this article, we’ll show you the MongoDB Data Insertion process and back it up with examples.

In MongoDB, this is done using the “insert” or “save” methods. The “insert” method stores data as a document and adds it directly to the database. The “save” method checks whether the document exists. If the data doesn’t exist, it creates a document; if it does, it updates the existing document.

In the example below, the MongoDB data insertion process is demonstrated using Node.js and the Mongoose library:

const mongoose = require("mongoose");

// We establish the database connection
mongoose.connect("mongodb://localhost:27017/mydatabase", {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

// We create a document schema for the collection
const employeeSchema = new mongoose.Schema({
  firstName: String,
  lastName: String,
  position: String,
  email: String
});

// We create the collection model
const Employee = mongoose.model("Employee", employeeSchema);

// Insert data
const newEmployee = new Employee({
  firstName: "John",
  lastName: "Doe",
  position: "Manager",
  email: "john.doe@company.com"
});

newEmployee.save(function(error) {
  if (error) {
    console.log(error);
  } else {
    console.log("Veri başarıyla eklendi.");
  }
});

In this example, it establishes a database connection and creates a document schema and collection model. Then it inserts data using the “save” method. If the insertion succeeds, it prints the success message to the console.

  1. MongoDB Official Documentation
  2. MongoDB Node.js
  3. Mongoose v5.9.25
  4. Inserting Data into a Collection in MongoDB

Share it if it helped

Write a comment