• MongoDB Realm数据库在Node中的使用


    本示例的演示是在Electron主线程中编写,由于浏览器环境的限制,realm依赖无法在Web端构建。当然如果需要在web端使用数据库存储,可以安装realm-web依赖。

    步骤一:安装realm依赖

    yarn add realm
    
    • 1

    步骤二:编写Model

    import Realm, { ObjectSchema } from "realm";
    
    export class UserModel extends Realm.Object<UserModel> {
        _id: number;
        uuid: string;
        name: string;
        username: string;
        header: string;
        group?: string | null;
        email?: string;
        static schema: ObjectSchema = {
            name: "User",
            properties: {
                _id: "int",
                uuid: "string",
                name: "string",
                username: "string",
                header: "string",
                // 表示group和email是可选的,可以为string 可以为null
                group: {type: "string", optional: true},
                email: {type: "string", optional: true},
            },
            // 主键为_id
            primaryKey: "_id",
        };
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    步骤三:封装DB类,连接数据库并进行操作

    import Realm from "realm";
    import {UserModel} from "./model";
    
    class DB {
    	private realm: Realm;
    	constructor() {
            this._open()
        }
        async _open() {
        	// 打开数据库 获取实例后方可进行增删改查操作
            this.realm = await Realm.open({
            	// 可以传入多个数据模型
                schema: [UserModel]
            });
        }
        _close() {
        	// 关闭数据库的连接,防止内存溢出
    		this.realm.close();
    	}
        getUsers(queryForm) {
        	// 获取User中所有的数据
    		return this.realm.objects<UserModel>("User");
    		// 当然也可以实现条件筛选
    		const userList = this.realm.objects<UserModel>("User");
    		return userList.filtered(`uuid = ${queryForm.uuid}`);
    		// 分页
    		const {pageNumber, pageSize} = queryForm;
    		const start = pageNumber * pageSize;
        	const end = (pageNumber + 1) * pageSize;
        	const userList = realm.objects<UserModel>("User").sorted("_id").slice(start, end);
        	return userList;
    	}
    	addUser(user) {
    		try {
                // 获取最后一项数据的ID 加1作为新数据的ID
                user._id = this.realm.objects<UserModel>("User").sorted("_id", true)[0]._id + 1 || 1;
                this.realm.write(() => {
                    this.realm.create("User", user);
                })
                return true
            } catch (e) {
                return false
            }
    	}
    	deleteUser(uuid) {
    		try {
    			// 从数据库中获取要删除的数据,可以是多个
                const user = this.realm.objects<UserModel>("User").filtered(`uuid == ${uuid}`);
                this.realm.write(() => {
                	// 进行删除操作
                    this.realm.delete(user);
                })
                return true
            } catch (e) {
                return false
            }
    	}
    	updateUser(params) {
    		try {
                this.realm.write(() => {
                	// 获取需要修改的数据
                	const user = this.realm.objects<UserModel>("User").filtered(`uuid == ${user.uuid}`);
                	// 修改后内容会被保存到realm数据库中
                    user.name = params.name
                    user.age + 1
                })
                return true
            } catch (e) {
                return false
            }
    	}
    }
    
    export default new DB();
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74

    最后new一个DB实例对象,返回出去,别的文件引入后即可调用相关的增删改查方法。

  • 相关阅读:
    计算机毕业设计springboot+vue基本微信小程序的社区后勤报修系统
    yum安装报错Error: rpmdb open failed
    【结构体】
    【 2023华为杯C题】大规模创新类竞赛评审方案研究(思路、代码......)
    常见的数据结构及应用
    Springboot毕设项目高校数字图书管理t1g8n(java+VUE+Mybatis+Maven+Mysql)
    黑龙江—等保测评三级安全设计思路
    怎样提高redis的命中率
    Word控件Spire.Doc 【文本】教程(2) ;在 C#、VB.NET 中从 Word 文档中提取文本
    品类超全的免费API接口整理分享
  • 原文地址:https://blog.csdn.net/weixin_43729943/article/details/136451006