mongoose-mongodb by pluginagentmarketplace/custom-plugin-nodejs
npx skills add https://github.com/pluginagentmarketplace/custom-plugin-nodejs --skill mongoose-mongodb通过优雅的对象建模库 Mongoose,掌握 Node.js 中的 MongoDB 数据库集成。
4 步完成连接和 CRUD:
npm install mongoosemongoose.connect(uri)const mongoose = require('mongoose');
mongoose.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true
});
mongoose.connection.on('connected', () => {
console.log('MongoDB connected');
});
const userSchema = new mongoose.Schema({
name: {
type: String,
required: [true, 'Name is required'],
trim: true,
minlength: 3,
maxlength: 50
},
email: {
type: String,
required: true,
unique: true,
lowercase: true
},
age: {
type: Number,
min: 18,
max: 120
},
role: {
type: String,
enum: ['user', 'admin'],
default: 'user'
}
}, {
timestamps: true // createdAt, updatedAt
});
const User = mongoose.model('User', userSchema);
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
// 创建
const user = await User.create({
name: 'John Doe',
email: 'john@example.com'
});
// 读取
const users = await User.find({ age: { $gte: 18 } });
const user = await User.findById(id);
const user = await User.findOne({ email: 'john@example.com' });
// 更新
const updated = await User.findByIdAndUpdate(
id,
{ name: 'Jane Doe' },
{ new: true, runValidators: true }
);
// 删除
await User.findByIdAndDelete(id);
await User.deleteMany({ age: { $lt: 18 } });
const postSchema = new mongoose.Schema({
title: String,
content: String,
author: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
});
// 填充关系
const post = await Post.findById(id).populate('author');
// post.author 现在是一个完整的用户对象
userSchema.index({ email: 1 }, { unique: true });
userSchema.index({ name: 1, age: -1 });
userSchema.pre('save', async function(next) {
if (this.isModified('password')) {
this.password = await bcrypt.hash(this.password, 10);
}
next();
});
userSchema.virtual('fullName').get(function() {
return `${this.firstName} ${this.lastName}`;
});
const stats = await User.aggregate([
{ $match: { age: { $gte: 18 } } },
{ $group: {
_id: '$role',
count: { $sum: 1 },
avgAge: { $avg: '$age' }
}},
{ $sort: { count: -1 } }
]);
// 比较操作符
User.find({ age: { $gt: 18 } }) // 大于
User.find({ age: { $gte: 18 } }) // 大于或等于
User.find({ age: { $lt: 65 } }) // 小于
User.find({ age: { $lte: 65 } }) // 小于或等于
User.find({ age: { $ne: 30 } }) // 不等于
// 逻辑操作符
User.find({ $and: [{ age: { $gte: 18 } }, { age: { $lte: 65 } }] })
User.find({ $or: [{ role: 'admin' }, { role: 'moderator' }] })
// 数组操作符
User.find({ tags: { $in: ['node', 'mongodb'] } })
User.find({ tags: { $nin: ['deprecated'] } })
// 正则表达式
User.find({ email: /gmail\.com$/ })
lean()(性能更好)在以下情况下使用 MongoDB 和 Mongoose:
每周安装量
353
仓库
GitHub 星标数
1
首次出现
2026 年 1 月 22 日
安全审计
安装于
claude-code242
opencode199
gemini-cli192
github-copilot188
codex185
cursor167
Master MongoDB database integration in Node.js with Mongoose, the elegant object modeling library.
Connect and CRUD in 4 steps:
npm install mongoosemongoose.connect(uri)const mongoose = require('mongoose');
mongoose.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true
});
mongoose.connection.on('connected', () => {
console.log('MongoDB connected');
});
const userSchema = new mongoose.Schema({
name: {
type: String,
required: [true, 'Name is required'],
trim: true,
minlength: 3,
maxlength: 50
},
email: {
type: String,
required: true,
unique: true,
lowercase: true
},
age: {
type: Number,
min: 18,
max: 120
},
role: {
type: String,
enum: ['user', 'admin'],
default: 'user'
}
}, {
timestamps: true // createdAt, updatedAt
});
const User = mongoose.model('User', userSchema);
// Create
const user = await User.create({
name: 'John Doe',
email: 'john@example.com'
});
// Read
const users = await User.find({ age: { $gte: 18 } });
const user = await User.findById(id);
const user = await User.findOne({ email: 'john@example.com' });
// Update
const updated = await User.findByIdAndUpdate(
id,
{ name: 'Jane Doe' },
{ new: true, runValidators: true }
);
// Delete
await User.findByIdAndDelete(id);
await User.deleteMany({ age: { $lt: 18 } });
const postSchema = new mongoose.Schema({
title: String,
content: String,
author: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
});
// Populate relationship
const post = await Post.findById(id).populate('author');
// post.author is now full user object
userSchema.index({ email: 1 }, { unique: true });
userSchema.index({ name: 1, age: -1 });
userSchema.pre('save', async function(next) {
if (this.isModified('password')) {
this.password = await bcrypt.hash(this.password, 10);
}
next();
});
userSchema.virtual('fullName').get(function() {
return `${this.firstName} ${this.lastName}`;
});
const stats = await User.aggregate([
{ $match: { age: { $gte: 18 } } },
{ $group: {
_id: '$role',
count: { $sum: 1 },
avgAge: { $avg: '$age' }
}},
{ $sort: { count: -1 } }
]);
// Comparison
User.find({ age: { $gt: 18 } }) // Greater than
User.find({ age: { $gte: 18 } }) // Greater or equal
User.find({ age: { $lt: 65 } }) // Less than
User.find({ age: { $lte: 65 } }) // Less or equal
User.find({ age: { $ne: 30 } }) // Not equal
// Logical
User.find({ $and: [{ age: { $gte: 18 } }, { age: { $lte: 65 } }] })
User.find({ $or: [{ role: 'admin' }, { role: 'moderator' }] })
// Array
User.find({ tags: { $in: ['node', 'mongodb'] } })
User.find({ tags: { $nin: ['deprecated'] } })
// Regex
User.find({ email: /gmail\.com$/ })
lean() for read-only queries (better performance)Use MongoDB with Mongoose when:
Weekly Installs
353
Repository
GitHub Stars
1
First Seen
Jan 22, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
claude-code242
opencode199
gemini-cli192
github-copilot188
codex185
cursor167
React 组合模式指南:Vercel 组件架构最佳实践,提升代码可维护性
106,200 周安装