# MiniDB 使用说明文档
## 概述
MiniDB 是懒猫微服官方提供的轻量级文档式数据库插件 ,专为懒猫微服容器化应用设计。它采用远程数据库架构,使用 lzcinit 中的 minidb 作为后端服务,为开发者提供简单易用的 NoSQL 数据操作接口。
## 核心特性
* **远程数据库架构**:基于懒猫微服容器化理念,数据存储与应用分离
* **文档式存储**:支持 JSON 格式的灵活数据结构
* **丰富查询语法**:提供类 MongoDB 的查询操作符
* **客户端库**:专为浏览器环境设计的 JavaScript SDK
* **即插即用**:无需复杂配置,开箱即用
## 安装与导入
### 在懒猫微服应用中使用
**1. 前端 package.json 配置**
```json
{
"dependencies": {
"@lazycatcloud/minidb": "latest"
}
}
```
**2. ES6 模块导入**
```javascript
import { MiniDB } from "@lazycatcloud/minidb";
```
**3. 在 HTML 中使用 Import Maps**
```html
<script type="importmap">
{
"imports": {
"@lazycatcloud/minidb": "https://cdn.skypack.dev/@lazycatcloud/minidb"
}
}
</script>
<script type="module">
import { MiniDB } from "@lazycatcloud/minidb";
// 使用代码
</script>
```
## 基础用法
### 初始化数据库连接
```javascript
import { MiniDB } from "@lazycatcloud/minidb";
// 创建数据库实例
const db = new MiniDB();
// 获取集合(类似于表)
const collection = db.getCollection("awesome");
```
### 数据插入与更新
```javascript
// 插入单个文档
await collection.upsert({
id: 1,
name: "张三",
age: 25,
department: "技术部"
});
// 批量插入文档
const docs = [...Array(100)].map((_, index) => {
const doc = {
index,
name: `name-${index}`,
};
if (index == 99) {
doc.last = true;
}
return doc;
});
await collection.upsert(docs);
```
## 查询操作详解
### 1. $in 查询 - 范围匹配
查询字段值在指定数组中的文档:
```javascript
// 查询 index 在 [0,1,2,3,4,5] 范围内的数据
const result = await collection
.find({ index: { $in: [0, 1, 2, 3, 4, 5] } }, { sort: ["index"] })
.fetch();
console.log(`找到 ${result.length} 条记录`);
result.forEach((doc, i) => {
console.assert(doc.index === i, "索引顺序正确");
});
```
### 2. $eq 查询 - 精确匹配
查询字段值等于指定值的文档,支持两种写法:
```javascript
// 简化写法
const user1 = await collection.findOne({ index: 5 });
// 完整写法
const user2 = await collection.findOne({ index: { $eq: 5 } });
console.assert(user1.index === 5 && user2.index === 5);
```
### 3. $gt 和 $gte 查询 - 大于比较
```javascript
// 查询大于指定条件的数据
const gtResult = await collection
.find({ index: { $gt: 90 } }, { sort: ["index"] })
.fetch();
console.assert(gtResult.length === 9); // 91-99,共9条
gtResult.forEach(doc => {
console.assert(doc.index > 90);
});
// 查询大于等于指定条件的数据
const gteResult = await collection
.find({ index: { $gte: 90 } }, { sort: ["index"] })
.fetch();
console.assert(gteResult.length === 10); // 90-99,共10条
gteResult.forEach(doc => {
console.assert(doc.index >= 90);
});
```
### 4. $lt 和 $lte 查询 - 小于比较
```javascript
// 查询小于指定条件的数据
const ltResult = await collection
.find({ index: { $lt: 9 } }, { sort: ["index"] })
.fetch();
console.assert(ltResult.length === 9); // 0-8,共9条
// 查询小于等于指定条件的数据
const lteResult = await collection
.find({ index: { $lte: 9 } }, { sort: ["index"] })
.fetch();
console.assert(lteResult.length === 10); // 0-9,共10条
```
### 5. 范围查询 - 组合条件
结合 $gte 和 $lte 实现范围查询:
```javascript
// 查询 index 在 5-10 之间的数据
const rangeResult = await collection
.find({ index: { $lte: 10, $gte: 5 } }, { sort: ["index"] })
.fetch();
console.assert(rangeResult.length === 6); // 5,6,7,8,9,10
rangeResult.forEach(doc => {
console.assert(doc.index <= 10 && doc.index >= 5);
});
```
### 6. $exists 查询 - 字段存在性
查询包含指定字段的文档:
```javascript
// 查询存在 last 字段的文档
const existsResult = await collection
.find({ $exists: "last" }, { sort: ["index"] })
.fetch();
console.assert(existsResult.length === 1);
console.assert(existsResult[0].index === 99);
```
### 7. $like 查询 - 模糊匹配
支持简单模糊匹配和正则表达式:
```javascript
// 简单模糊查询
const likeResult = await collection
.find({ name: { $like: `name-1` } }, { sort: ["index"] })
.fetch();
console.assert(likeResult.length === 11); // name-1, name-10~name-19
// 正则表达式查询
const regexResult = await collection
.find({ name: { $like: `name-1[5678]` } }, { sort: ["index"] })
.fetch();
console.assert(regexResult.length === 4); // name-15, name-16, name-17, name-18
regexResult.forEach(doc => {
console.assert(doc.index >= 15 && doc.index <= 18);
});
```
## 高级功能
### 排序和分页
```javascript
// 按字段排序(默认升序)
const sortedResult = await collection
.find({}, { sort: ["index"] })
.fetch();
// 多字段排序
const multiSortResult = await collection
.find({}, { sort: ["department", "age"] })
.fetch();
// 分页查询(需要结合业务逻辑实现)
const pageSize = 10;
const page = 1;
const paginatedResult = await collection
.find({}, { sort: ["index"] })
.fetch();
const pageData = paginatedResult.slice((page - 1) * pageSize, page * pageSize);
```
### 集合管理
```javascript
// 删除整个集合
await db.removeCollection("example");
// 获取多个集合
const usersCollection = db.getCollection("users");
const ordersCollection = db.getCollection("orders");
```
## 在懒猫微服应用中的最佳实践
### 1. 前后端架构建议
**前端使用 MiniDB(推荐)**
```javascript
// 在 React 组件中使用
import React, { useState, useEffect } from 'react';
import { MiniDB } from "@lazycatcloud/minidb";
const UserManager = () => {
const [users, setUsers] = useState([]);
const [db] = useState(() => new MiniDB());
const [collection] = useState(() => db.getCollection("users"));
useEffect(() => {
loadUsers();
}, []);
const loadUsers = async () => {
try {
const result = await collection.find({}, { sort: ["name"] }).fetch();
setUsers(result);
} catch (error) {
console.error('加载用户失败:', error);
}
};
const addUser = async (userData) => {
try {
await collection.upsert(userData);
await loadUsers(); // 重新加载数据
} catch (error) {
console.error('添加用户失败:', error);
}
};
return (
<div>
{/* 用户界面组件 */}
</div>
);
};
```
**后端提供辅助服务**
```javascript
// server.js - 提供数据导出、统计等服务
const express = require('express');
const app = express();
// 健康检查
app.get('/api/health', (req, res) => {
res.json({ status: 'ok', timestamp: new Date().toISOString() });
});
// 数据统计接口
app.get('/api/stats', async (req, res) => {
try {
// 这里可以调用其他服务或进行复杂计算
res.json({ message: '统计数据' });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.listen(3000, () => {
console.log('辅助服务启动成功');
});
```
### 2. lzc-manifest.yml 配置
```yaml
name: MiniDB应用示例
package: cloud.lazycat.app.minidbdemo
version: 1.0.0
description: 使用MiniDB的懒猫微服应用
application:
subdomain: minidbdemo
routes:
- /=file:///lzcapp/pkg/content/web
- /api/=exec://3000,./lzcapp/pkg/content/backend/run.sh
```
### 3. 错误处理和调试
```javascript
class MiniDBService {
constructor() {
this.db = new MiniDB();
this.retryCount = 3;
}
async withRetry(operation) {
for (let i = 0; i < this.retryCount; i++) {
try {
return await operation();
} catch (error) {
console.warn(`操作失败,第 ${i + 1} 次重试:`, error.message);
if (i === this.retryCount - 1) throw error;
await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
}
}
}
async safeQuery(collection, query, options = {}) {
return this.withRetry(async () => {
return await collection.find(query, options).fetch();
});
}
}
// 使用示例
const dbService = new MiniDBService();
const collection = dbService.db.getCollection("products");
try {
const products = await dbService.safeQuery(collection, { category: "electronics" });
console.log('查询成功:', products);
} catch (error) {
console.error('查询失败:', error);
}
```
## 注意事项和限制
### 1. 已知问题
* **$ne 操作符**:目前存在 bug,暂时不要使用
* **浏览器兼容性**:需要支持 ES6 模块的现代浏览器
* **网络依赖**:作为远程数据库,需要稳定的网络连接
### 2. 性能优化建议
```javascript
// 避免频繁的小批量操作
// ❌ 不推荐
for (const item of items) {
await collection.upsert(item);
}
// ✅ 推荐
await collection.upsert(items);
// 合理使用索引字段进行查询
// ✅ 推荐:使用有索引的字段
const result = await collection.find({ id: userId });
// 限制返回数据量
const recentItems = await collection
.find({ createTime: { $gte: lastWeek } })
.fetch()
.then(results => results.slice(0, 100));
```
### 3. 数据安全
```javascript
// 输入验证
function validateUserInput(data) {
const allowedFields = ['name', 'email', 'age'];
const sanitized = {};
for (const field of allowedFields) {
if (data[field] !== undefined) {
sanitized[field] = data[field];
}
}
return sanitized;
}
// 使用示例
const userData = validateUserInput(req.body);
await collection.upsert(userData);
```
## 总结
MiniDB 是懒猫微服生态中的重要组件,为开发者提供了简单易用的文档式数据库解决方案。通过本文档的详细说明和代码示例,开发者可以:
1. **快速上手**:理解 MiniDB 的核心概念和基础用法
2. **掌握查询**:熟练使用各种查询操作符进行数据检索
3. **最佳实践**:在懒猫微服应用中正确集成和使用 MiniDB
4. **避免陷阱**:了解已知限制和性能优化要点
MiniDB 特别适合中小型应用的数据存储需求,结合懒猫微服的容器化架构,可以快速构建现代化的 Web 应用。随着懒猫微服生态的不断完善,MiniDB 也将持续优化和增强功能。
相关链接:
Refly画布