阿里云主机折上折
  • 微信号
Current Site:Index > Install Mongoose using npm.

Install Mongoose using npm.

Author:Chuan Chen 阅读数:61714人阅读 分类: MongoDB

Installing Node.js and npm

Before installing Mongoose, ensure that Node.js and npm are already installed on your system. Node.js is a JavaScript runtime built on Chrome's V8 engine, and npm is the package manager for Node.js. You can check if they are installed by running the following commands:

node -v
npm -v

If they are not installed, download and install the latest version from the Node.js official website. npm will be included automatically after installation.

Initializing a Project

Create a new directory and initialize a Node.js project:

mkdir mongoose-demo
cd mongoose-demo
npm init -y

This will generate a package.json file to record the project's dependencies and configuration information.

Installing Mongoose

Installing Mongoose using npm is straightforward. Simply run the following command:

npm install mongoose

This will automatically download the latest stable version of Mongoose and add it to the package.json's dependencies. To install a specific version, specify the version number:

npm install mongoose@6.0.0

Verifying the Installation

After installation, you can verify whether Mongoose was successfully installed with the following code:

// test.js
const mongoose = require('mongoose');
console.log(mongoose.version);

Run this script:

node test.js

If the Mongoose version number is output, the installation was successful.

Connecting to a MongoDB Database

Once Mongoose is installed, you can start connecting to a MongoDB database. First, ensure the MongoDB service is running, then use the following code to establish a connection:

const mongoose = require('mongoose');

// Connect to the local MongoDB database
mongoose.connect('mongodb://localhost:27017/myapp', {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

// Get the connection object
const db = mongoose.connection;

// Listen for the connection success event
db.on('connected', () => {
  console.log('MongoDB connection successful');
});

// Listen for the connection error event
db.on('error', (err) => {
  console.error('MongoDB connection error:', err);
});

Defining Schema and Model

Mongoose uses Schema to define data structures and then creates Models from the Schema:

// Define a user Schema
const userSchema = new mongoose.Schema({
  name: String,
  age: Number,
  email: {
    type: String,
    required: true,
    unique: true
  },
  createdAt: {
    type: Date,
    default: Date.now
  }
});

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

Basic CRUD Operations

Creating Documents

// Create a new user
const newUser = new User({
  name: 'Zhang San',
  age: 25,
  email: 'zhangsan@example.com'
});

// Save to the database
newUser.save()
  .then(doc => {
    console.log('User created successfully:', doc);
  })
  .catch(err => {
    console.error('Failed to create user:', err);
  });

Querying Documents

// Query all users
User.find()
  .then(users => {
    console.log('All users:', users);
  });

// Conditional query
User.findOne({ name: 'Zhang San' })
  .then(user => {
    console.log('Found user:', user);
  });

Updating Documents

// Update user age
User.updateOne({ name: 'Zhang San' }, { age: 26 })
  .then(result => {
    console.log('Update result:', result);
  });

Deleting Documents

// Delete a user
User.deleteOne({ name: 'Zhang San' })
  .then(result => {
    console.log('Delete result:', result);
  });

Advanced Queries

Mongoose provides a rich set of query methods:

// Pagination query
User.find()
  .skip(10)  // Skip the first 10 records
  .limit(5)  // Return 5 records
  .sort({ createdAt: -1 })  // Sort by creation time in descending order
  .exec()
  .then(users => {
    console.log('Pagination result:', users);
  });

// Aggregation query
User.aggregate([
  { $match: { age: { $gt: 20 } } },
  { $group: { _id: null, averageAge: { $avg: "$age" } } }
])
.then(result => {
  console.log('Average age:', result);
});

Middleware and Hooks

Mongoose supports middleware functions that execute before or after specific operations:

userSchema.pre('save', function(next) {
  console.log('About to save user:', this);
  next();
});

userSchema.post('save', function(doc) {
  console.log('User saved:', doc);
});

Data Validation

Mongoose includes built-in validators:

const productSchema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, 'Product name cannot be empty'],
    minlength: [3, 'Name must be at least 3 characters'],
    maxlength: [50, 'Name cannot exceed 50 characters']
  },
  price: {
    type: Number,
    min: [0, 'Price cannot be negative'],
    validate: {
      validator: function(v) {
        return v % 0.5 === 0;  // Price must be a multiple of 0.5
      },
      message: 'Price must be a multiple of 0.5'
    }
  }
});

Index Optimization

Add indexes to frequently queried fields:

userSchema.index({ email: 1 }, { unique: true });  // Unique index
userSchema.index({ name: 1, age: -1 });  // Compound index

Transaction Support

Mongoose supports MongoDB transactions:

const session = await mongoose.startSession();
session.startTransaction();

try {
  const user = await User.create([{ name: 'Li Si' }], { session });
  await Account.create([{ userId: user[0]._id, balance: 100 }], { session });
  await session.commitTransaction();
} catch (error) {
  await session.abortTransaction();
  throw error;
} finally {
  session.endSession();
}

Performance Optimization

  1. Use lean() to return plain JavaScript objects, reducing memory usage:
User.find().lean().exec()
  .then(users => {
    // users are plain JS objects, not Mongoose documents
  });
  1. Use bulkWrite for batch operations:
User.bulkWrite([
  { insertOne: { document: { name: 'Wang Wu' } } },
  { updateOne: { filter: { name: 'Li Si' }, update: { age: 30 } } }
]);

Troubleshooting Common Issues

  1. Connection disconnection issues:
// Auto-reconnect
mongoose.connection.on('disconnected', () => {
  mongoose.connect('mongodb://localhost:27017/myapp', {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    autoReconnect: true,
    reconnectTries: Number.MAX_VALUE,
    reconnectInterval: 1000
  });
});
  1. Deprecation warnings handling:
mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);

Practical Application Example

Building a simple user management system:

// app.js
const express = require('express');
const mongoose = require('mongoose');
const app = express();

// Connect to the database
mongoose.connect('mongodb://localhost:27017/user-manager', {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

// Define the user model
const User = mongoose.model('User', new mongoose.Schema({
  username: { type: String, required: true },
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true }
}));

// API routes
app.get('/users', async (req, res) => {
  try {
    const users = await User.find();
    res.json(users);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

app.listen(3000, () => {
  console.log('Server running at http://localhost:3000');
});

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.