Creating Documents
Swipe um das Menü anzuzeigen
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.
Danke für Ihr Feedback!
Fragen Sie AI
Fragen Sie AI
Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen