Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Oppiskele Creating Documents | CRUD Operations with Mongoose
MongoDB and Mongoose Essentials

Creating Documents

Pyyhkäise näyttääksesi valikon

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?

Valitse kaikki oikeat vastaukset

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 3. Luku 1

Kysy tekoälyä

expand

Kysy tekoälyä

ChatGPT

Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme

Osio 3. Luku 1
some-alt