Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Creating Documents | CRUD Operations with Mongoose
MongoDB and Mongoose Essentials

Creating Documents

Свайпніть щоб показати меню

To create and save a new document in MongoDB using Mongoose, you first need to define a model based on your schema. Once you have the model, you can instantiate it with the data you want to store, and then call the save() method to persist it to the database. Here is a code example with comments explaining each step:

// Import the Mongoose library
const mongoose = require('mongoose');

// Define a schema for a simple User collection
const userSchema = new mongoose.Schema({
  name: { type: String, required: true }, // Name is required
  email: { type: String, required: true, unique: true }, // Email is required and must be unique
  age: Number // Age is optional
});

// Create a model from the schema
const User = mongoose.model('User', userSchema);

// Create a new instance of the User model with data
const newUser = new User({
  name: 'Alice',
  email: 'alice@example.com',
  age: 30
});

// Save the new user document to the database
newUser.save()
  .then((savedUser) => {
    console.log('User saved:', savedUser);
  })
  .catch((error) => {
    console.error('Error saving user:', error);
  });

The save() method is used to insert a new document into the database. When you call save() on a Mongoose model instance, Mongoose first validates the data against the schema rules you defined. If the data passes validation, the document is written to the database. If any validation fails (such as missing required fields or violating uniqueness), the promise is rejected and an error is returned. In the code example above, the name and email fields are required, so if you try to save a user without these fields, Mongoose will throw a validation error and the document will not be saved. This built-in validation helps ensure data integrity before anything is stored in your MongoDB collection.

question mark

Which of the following statements about creating documents with Mongoose and the save() method are correct?

Виберіть усі правильні відповіді

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 3. Розділ 1

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

Секція 3. Розділ 1
some-alt