Electron中用Redis-OM更新Redis数据时报错TypeError: entity.toRedisJson is not a function
解决Redis-OM中TypeError: entity.toRedisJson is not a function错误
问题原因
你遇到的错误核心是异步方法未正确处理:
albumRepository.fetch()是异步操作,返回的是Promise对象,直接赋值给album会导致变量存储的不是Entity实例,而是Promise。后续修改属性并调用save时,Redis-OM无法在Promise对象上找到toRedisJson方法,因此抛出错误。- 另外,
albumRepository.save()同样是异步方法,之前的代码未处理异步逻辑,也会引发未处理的Promise拒绝警告。
修复方案
将代码包裹在异步函数中,用await等待异步方法执行完成,确保拿到正确的Entity实例后再进行修改和保存操作。
修正后的完整代码
const { Entity, Schema, Client, Repository } = require('redis-om') const client = new Client() // 用async函数包裹所有异步逻辑 async function run() { await client.open('redis://localhost:6379') class Album extends Entity {} const albumSchema = new Schema(Album, { artist: { type: 'string' }, title: { type: 'text' }, year: { type: 'number' }, genres: { type: 'string[]' }, outOfPublication: { type: 'boolean' } }) const albumRepository = client.fetchRepository(albumSchema); // 初始化仓库索引(推荐执行,确保Schema配置生效) await albumRepository.createIndex() // 保存新数据 const album = albumRepository.createEntity() album.artist = 'Mushroomhead' album.title = 'The Righteous & The Butterfly' album.year = 2014 album.genres = [ 'metal' ] album.outOfPublication = true // 等待保存完成,拿到带ID的实体 const savedAlbum = await albumRepository.save(album) console.log('新专辑ID:', savedAlbum.entityId) // 获取并修改现有记录 // 等待fetch完成,拿到真正的Entity实例 const fetchedAlbum = await albumRepository.fetch(savedAlbum.entityId); fetchedAlbum.title = 'The Righteous & The Butterfly (Updated)' // 等待更新保存完成 const updatedAlbum = await albumRepository.save(fetchedAlbum) console.log('更新后的专辑:', updatedAlbum) } // 执行函数并捕获错误 run().catch(err => console.error('操作错误:', err))
额外注意事项
- 所有Redis-OM的异步方法(
open、fetch、save、createIndex等)都必须用await处理,否则会拿到Promise对象而非实际数据。 - Electron环境下Redis-OM与Redis完全兼容,只要Redis服务正常运行,且Electron主进程能正常连接到Redis服务即可。
内容的提问来源于stack exchange,提问作者Andrew Liu
相关产品推荐
相关产品推荐

