Mongoose 使用简介

Mongoose 是 Node.js 环境下的 MongoDB 对象数据模型(ODM)库,提供模式验证和类型转换等功能,便于管理 MongoDB 集合和文档。

安装 Mongoose

在 Node.js 项目中安装 Mongoose:

bash 复制代码
npm install mongoose

连接 MongoDB

在 Node.js 应用中使用 Mongoose 连接 MongoDB 数据库:

javascript 复制代码
const mongoose = require('mongoose');

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

mongodb://localhost:27017/myapp 是数据库的 URI,myapp 是数据库名称。useNewUrlParseruseUnifiedTopology 是确保使用新 MongoDB 驱动的连接选项。

定义模型

使用 Schema 定义数据结

构。模型基于 Schema 构建,代表数据库中的集合,用于查询和操作数据。

javascript 复制代码
const Schema = mongoose.Schema;

const blogSchema = new Schema({
  title: String,
  author: String,
  body: String,
  comments: [{ body: String, date: Date }],
  date: { type: Date, default: Date.now },
  hidden: Boolean,
  meta: {
    votes: Number,
    favs: Number
  }
});

const Blog = mongoose.model('Blog', blogSchema);

使用模型进行 CRUD 操作

创建文档:

javascript 复制代码
const myBlog = new Blog({
  title: 'Mongoose Usage',
  author: 'John Doe',
  body: 'Mongoose is easy to use with MongoDB.'
});

myBlog.save(err => {
  if (err) console.error(err);
});

查询文档:

javascript 复制代码
Blog.find({ author: 'John Doe' }, (err, blogs) => {
  if (err) console.error(err);
});

更新文档:

javascript 复制代码
Blog.updateOne({ title: 'Mongoose Usage' }, { body: 'Updated content' }, err => {
  if (err) console.error(err);
});

删除文档:

javascript 复制代码
Blog.deleteOne({ title: 'Mongoose Usage' }, err => {
  if (err) console.error(err);
});

中间件、自定义验证和虚拟属性

中间件(Hooks)可在动作前后执行代码:

javascript 复制代码
blogSchema.pre('save', function(next) {
  // 执行保存前的操作
  next();
});

自定义验证:

javascript 复制代码
blogSchema.path('title').validate(val => {
  return val.length < 120;
}, 'Title too long');

虚拟属性:

javascript 复制代码
blogSchema.virtual('summary').get(function() {
  return this.title + ' - ' + this.author;
});

Mongoose 通过 Schema 和模型以及其他高级特性简化了 Node.js 应用中与 MongoDB 交互的复杂性。通过这些工具,可以有效管理数据库操作。


English version

Introduction to Mongoose Usage

Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It offers schema validation and typecasting, making the management of MongoDB collections and documents more convenient.

Install Mongoose

To install Mongoose in a Node.js project:

bash 复制代码
npm install mongoose

Connect to MongoDB

Use Mongoose to connect to a MongoDB database within a Node.js application:

javascript 复制代码
const mongoose = require('mongoose');

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

The mongodb://localhost:27017/myapp is the database URI, with myapp being the database name. The options useNewUrlParser and useUnifiedTopology ensure the use of the new MongoDB driver for connections.

Define a Model

Data structures are defined using Schemas. Models are built based on Schemas, representing collections in the database for querying and manipulating data.

javascript 复制代码
const Schema = mongoose.Schema;

const blogSchema = new Schema({
  title: String,
  author: String,
  body: String,
  comments: [{ body: String, date: Date }],
  date: { type: Date, default: Date.now },
  hidden: Boolean,
  meta: {
    votes: Number,
    favs: Number
  }
});

const Blog = mongoose.model('Blog', blogSchema);

Perform CRUD Operations Using the Model

To create a document:

javascript 复制代码
const myBlog = new Blog({
  title: 'Mongoose Usage',
  author: 'John Doe',
  body: 'Mongoose is easy to use with MongoDB.'
});

myBlog.save(err => {
  if (err) console.error(err);
});

To query documents:

javascript 复制代码
Blog.find({ author: 'John Doe' }, (err, blogs) => {
  if (err) console.error(err);
});

To update a document:

javascript 复制代码
Blog.updateOne({ title: 'Mongoose Usage' }, { body: 'Updated content' }, err => {
  if (err) console.error(err);
});

To delete a document:

javascript 复制代码
Blog.deleteOne({ title: 'Mongoose Usage' }, err => {
  if (err) console.error(err);
});

Middleware, Custom Validation, and Virtual Properties

Middleware (Hooks) allows execution of code before or after certain actions:

javascript 复制代码
blogSchema.pre('save', function(next) {
  // perform actions before saving
  next();
});

Custom validation:

javascript 复制代码
blogSchema.path('title').validate(val => {
  return val.length < 120;
}, 'Title too long');

Virtual properties:

javascript 复制代码
blogSchema.virtual('summary').get(function() {
  return this.title + ' - ' + this.author;
});

Mongoose simplifies the complexity of interacting with MongoDB in Node.js applications through Schemas and Models, along with other advanced features. These tools effectively facilitate database operations.

相关推荐
生椰拿铁You31 分钟前
09 —— Webpack搭建开发环境
前端·webpack·node.js
酷酷的威朗普6 小时前
医院绩效考核系统
javascript·css·vue.js·typescript·node.js·echarts·html5
前端李易安18 小时前
Webpack 热更新(HMR)详解:原理与实现
前端·webpack·node.js
Ztiddler1 天前
【npm设置代理-解决npm网络连接error network失败问题】
前端·后端·npm·node.js·vue
前端青山1 天前
webpack进阶(一)
前端·javascript·webpack·前端框架·node.js
老攀呀1 天前
安装多个nodejs版本(nvm)
node.js
佚名程序员1 天前
【Node.js】全面解析 Node.js 安全最佳实践:保护您的应用
安全·node.js
zxg_神说要有光2 天前
快速入门 AI:调用 AI 接口生成 React 组件
前端·javascript·node.js
佚名程序员2 天前
【Node.js】深入理解 V8 JavaScript 引擎
前端·javascript·node.js
赵闪闪1682 天前
Node.js 安装与开发环境配置全指南
node.js