📜  mongoosejs - Javascript (1)

📅  最后修改于: 2023-12-03 15:03:02.525000             🧑  作者: Mango

Mongoosejs - Javascript

Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment. It provides a wrapper for MongoDB operations, making it easier to interact with the database using Javascript.

Features

Mongoose provides the following features:

  • Define schemas for your data
  • Define models based on your schemas
  • Define static and instance methods on your models
  • Query the database using a fluent API
  • Middleware support
  • Validation support
Installation

To install Mongoose, use npm:

npm install mongoose
Usage

To start using Mongoose, first require it in your code:

const mongoose = require('mongoose');

Next, connect to your MongoDB database:

mongoose.connect('mongodb://localhost:27017/mydatabase', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

Define a schema for your data:

const userSchema = new mongoose.Schema({
  name: { type: String, required: true },
  email: { type: String, required: true, unique: true },
  age: { type: Number },
});

Create a model based on the schema:

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

Use the model to interact with the database:

const newUser = new User({
  name: 'John',
  email: 'john@example.com',
  age: 30,
});

newUser.save((err, user) => {
  if (err) {
    console.error(err);
  } else {
    console.log('Saved user:', user);
  }
});
Querying the database

Mongoose provides a fluent API for querying the database. For example, to find all users with an age greater than 25:

User.find({ age: { $gt: 25 } }, (err, users) => {
  if (err) {
    console.error(err);
  } else {
    console.log('Users:', users);
  }
});

For more information on querying the database with Mongoose, see the official documentation.

Middleware

Mongoose supports middleware functions that can be executed before or after certain events on a model, such as saving or removing a document. For example, to hash a user's password before saving:

userSchema.pre('save', function (next) {
  const user = this;

  if (!user.isModified('password')) {
    return next();
  }

  bcrypt.genSalt(10, (err, salt) => {
    if (err) {
      return next(err);
    }

    bcrypt.hash(user.password, salt, (err, hash) => {
      if (err) {
        return next(err);
      }

      user.password = hash;
      next();
    });
  });
});
Validation

Mongoose provides built-in validation for your schemas. For example, to require a field to be non-empty:

const userSchema = new mongoose.Schema({
  name: { type: String, required: true },
  email: { type: String, required: true, unique: true },
  age: { type: Number, min: 18 },
});

For more information on validation with Mongoose, see the official documentation.

Conclusion

Mongoose is a powerful tool for working with MongoDB using Javascript. With support for schemas, models, middleware, validation, and more, it can make working with the database a breeze. For more information, see the official documentation.