📅  最后修改于: 2023-12-03 15:03:02.525000             🧑  作者: Mango
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.
Mongoose provides the following features:
To install Mongoose, use npm:
npm install mongoose
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);
}
});
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.
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();
});
});
});
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.
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.