今天的新知识#6(猫鼬)
今日概览:
大家好❤❤❤!希望你们都过得好。今天,我开始探索 Mongoose。凭借我对 MongoDB 的扎实了解,我觉得现在是深入研究 Mongoose 的好时机,因为它为与 MongoDB 交互提供了更高级别的抽象。以下是我今天学到的内容的总结。
猫鼬
Mongoose 是 MongoDB 和 Node.js 的一个流行对象数据建模 (ODM) 库。它充当 Node.js 应用程序和 MongoDB 数据库之间的桥梁,使您能够定义数据结构并以更结构化和更高效的方式与 MongoDB 交互。当您将数据发送到 MongoDB 时,mongoose 会将数据与模型进行映射,如果数据与模型结构匹配,则在 MongoDB 驱动程序的帮助下,数据将发送到 mongoDB。因此它确保了数据的有效性。
为什么我们应该使用 Mongoose?
连接到 MongoDB
Mongoose 使用 URI 建立与 MongoDB 数据库的连接。连接后,它会提供与数据库交互的方法。
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/mydatabase')
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.error('Connection error:', err));架构:
Mongoose 中的架构是定义 MongoDB 集合中文档的结构、数据类型、默认值和验证规则的蓝图。它确保数据一致性,并使 MongoDB 集合的使用更加结构化。
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
// Required field of type String
email: { type: String, required: true },
// Required and must be unique
age: { type: Number, min: 0 },
// Number with minimum value validation
isAdmin: { type: Boolean, default: false },
// Default value if not provided
createdAt: { type: Date, default: Date.now }
// Automatically sets the current date
});常见架构属性
`type`:指定数据类型(字符串、数字、布尔值、日期、缓冲区、ObjectId、数组等)。
`required`:确保必须提供该字段。
default:如果未提供,则设置默认值。
`unique`:确保字段中的值在文档中是唯一的。
`enum`:指定字段的允许值。
`validate`:提供自定义验证逻辑。
模型
在 Mongoose 中,模型是一个提供与特定 MongoDB 集合交互的接口的类。
const User = mongoose.model('User', userSchema);CRUD 操作
Mongoose 简化了创建、读取、更新和删除文档等操作。具体方法如下:
//create
const newUser = new User({
name: 'Alice',
email: 'alice@example.com',
age: 25
});
await newUser.save();
// Saves the document to MongoDB
//read
const users = await User.find();
// Retrieves all users
const user = await User.findOne({ email: 'alice@example.com' });
// Finds a specific user
//update
await User.updateOne(
{ email: 'alice@example.com' },
{ age: 26 }
);
//delete
await User.deleteOne({ email: 'alice@example.com' });关系(人口)
在 Mongoose 中,填充 (population) 功能使您能够处理存储在不同集合中的文档之间的关系。
const postSchema = new mongoose.Schema({
title: String,
author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
});
const Post = mongoose.model('Post', postSchema);
// Populate author details when querying posts
const posts = await Post.find().populate('author');验证
Mongoose 提供强大的内置验证功能,以确保数据在保存到数据库之前的完整性。您可以直接在架构中定义验证规则,以强制执行必填字段、值范围、自定义检查等约束。
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
// Name is mandatory
email: { type: String, required: [true, 'Email is required'], match: /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/ }
// Custom error message and regex validation
price: { type: Number, min: 0, max: 1000 }
// Price must be between 0 and 1000
});
title: { type: String, minlength: 5, maxlength: 100 }
// Title length must be 5–100 characters
age: {
type: Number,
validate: {
validator: function (value) {
return value >= 18;
// Age must be at least 18
},
message: 'Age must be 18 or older'
// Custom error message
}
}
});
//custom validation查询构建
Mongoose 提供了功能强大、可链接的 API,可轻松构建和执行数据库查询。查询是使用查询对象构建的,可让您过滤、投影、排序和分页数据。
const users = await User.find({ age: { $gte: 18 } });
const user = await User.findOne({ email: 'example@example.com' });
const user = await User.findById('648e5f2a7a1b2c6d4e5f3a4d');查询链
Mongoose 查询是可链接的,这意味着您可以组合过滤器、投影和选项。
const users = await User.find({ age: { $gte: 18 } }) // Filter users by age
.select('name email') // Project only 'name' and 'email' fields
.sort({ name: 1 }) // Sort by name in ascending order
.limit(10); // Limit to 10 results*
结论:
这就是我今天学到的关于猫鼬的全部内容。我也练习了之前学到的其他东西。希望很快能和你聊天。再见🖐。