[Node.js] Use Realm Object Database with Node.js

Realm is an ACID compliant object database. In this lesson, you will learn how to install Realm, define schemas for your data, perform CRUD operations and persist your data to the filesystem.

 

复制代码
var Realm = require('realm');

const PetShema = {
    name: 'Pet',
    properties: {
        name: 'string',
        species: 'string',
        age: 'int',
        hasFur: 'bool'
    }
};

const PersonSchema = {
    name: 'Person',
    primaryKey: 'id',
    properties: {
        id: 'int',
        name: 'string',
        birthday: 'date',
        pet: {type: 'Pet'}
    }
};

let realm = new Realm({
    path: './people.realm',
    schema: [PetShema, PersonSchema]
});

realm.write(() => {
    realm.create('Person', {
        id: 0,
        name: 'Bpb',
        birthday: new Date('2001-10-10'),
        pet: {
            name: 'Fluffy',
            species: 'Cat',
            age: 4,
            hasFur: true
        }
    })
});

realm.write(() => {

    realm.create('Person', {
        id: 1,
        name: 'Tom',
        birthday: new Date('1989-12-17'),
        pet: {
            name: 'Umi',
            species: 'Dog',
            age: 5,
            hasFur: true
        }
    });
});


let people = realm.objects('Person');
let pets = realm.objects('Pet');

console.log("people", JSON.stringify(people, null, 2));
console.log("pets", JSON.stringify(pets, null, 2));

let filteredPets = pets.filtered('age < 5');
console.log("filteredPets", JSON.stringify(filteredPets, null, 2));

let multiFilterPets = pets.filtered('hasFur = true AND name BEGINSWITH "F"');
console.log("multiFilterPets", JSON.stringify(multiFilterPets, null, 2));

let sortedAge = pets.sorted('age');
console.log("sortedAge", JSON.stringify(sortedAge, null, 2));

// Overwrite the existing Person
realm.write(() => {
    realm.create('Person', {id: 0, name: 'Jake'}, true)
});
console.log("Person", JSON.stringify(people, null, 2));

// delete
let person = realm.objects('Person').filtered('id = 0');
realm.write(() => {
    realm.delete(person);
});
console.log("After delete", JSON.stringify(people, null, 2));
复制代码

 

The data is stored in the local files:

 

Github

posted @   Zhentiw  阅读(467)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2014-11-28 [CSS3 Animation] TweenMax.staggerTo()
点击右上角即可分享
微信分享提示