📅  最后修改于: 2023-12-03 14:44:46.692000             🧑  作者: Mango
Mongoose is a Node.js library used to manage MongoDB connections and perform various operations. It supports object modeling and schema definition with an API inspired by the well-known ORM tools.
To install Mongoose using npm, run this command:
npm install mongoose
To use Mongoose in your project, add the following code to import the module:
const mongoose = require('mongoose');
To connect Mongoose to your MongoDB server, use the connect
method and specify the MongoDB URL.
mongoose.connect('mongodb://localhost/my_database', { useNewUrlParser: true , useUnifiedTopology: true });
Before you can perform operations on a MongoDB collection, you need to define a schema that represents the data structure.
const userSchema = new mongoose.Schema({
name: String,
email: { type: String, unique: true },
age: Number
});
With the schema defined, you can create a model that represents a MongoDB collection and provides an API to perform various operations on that collection.
const User = mongoose.model('User', userSchema);
You can perform MongoDB queries using various methods provided by Mongoose. For example, to find a user by their email address, you can use the findOne
method:
const user = await User.findOne({ email: 'user@example.com' });
To find all users with a certain age, you can use the find
method:
const users = await User.find({ age: 25 });
To create and save a new document to the database, you can use the create
method:
const user = await User.create({
name: 'John Doe',
email: 'john.doe@example.com',
age: 25
});
You can also create a new instance of a model and then save it:
const user = new User({
name: 'John Doe',
email: 'john.doe@example.com',
age: 25
});
await user.save();
To update an existing document, you can use the updateOne
method:
await User.updateOne({ email: 'john.doe@example.com' }, { age: 30 });
To delete documents from the database, you can use the deleteOne
or deleteMany
methods:
await User.deleteOne({ email: 'john.doe@example.com' });
await User.deleteMany({ age: { $gte: 30 } });
Mongoose is a powerful MongoDB library that provides an easy-to-use API for managing connections, defining schemas, and performing database operations. With Mongoose, you can streamline your Node.js development and take full advantage of MongoDB's flexibility and scalability.