You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular服务中Relational Pouch相关方法无法正常调用问题求助

问题原因与解决方案

核心错误点

  1. 对relational-pouch的setSchemaAPI返回值理解错误:setSchema调用后会直接将关系操作对象挂载到原PouchDB实例的rel属性上,本身无有效返回值,你将返回值赋值给this.rel,自然不存在save方法。
  2. 插件方法命名冲突与调用参数错误:pouchdb-find会在PouchDB实例根路径挂载find方法,relational-pouch的find方法在db.rel路径下,且第一个必填参数为实体类型,你直接传id调用时触发了pouchdb-find的参数校验,抛出错误。
  3. relational-pouch的findAPI使用不符合规范,缺少第一个实体类型参数。

修正后的代码

import PouchDB from 'pouchdb-browser'
import find from 'pouchdb-find'
import rel from 'relational-pouch'

// 请确保你的schema定义符合relational-pouch规范,示例如下:
const schema = [
  {
    singular: 'project',
    plural: 'projects',
    relations: {
      books: { hasMany: 'book' }
    }
  },
  {
    singular: 'book',
    plural: 'books'
  }
]

@Injectable({
    providedIn: 'root'
})
export class PouchDBService {
    public base_db: PouchDB.Database
    public rel

    constructor() {
        PouchDB.plugin(find)
        PouchDB.plugin(rel)
        this.base_db = new PouchDB('Eeeek')
        // 仅调用setSchema,不需要接收返回值
        this.base_db.setSchema(schema)
        // 从db实例上取挂载好的rel操作对象
        this.rel = this.base_db.rel
        // 正常调用save方法
        this.rel.save('project', {
            name: 'George R. R. Martin', id: 1, books: [6, 7]
        })
    }

    // 按ID查询project示例
    getProjectById(id: number) {
        // relational-pouch的find第一个参数为实体名,第二个为查询条件/ID
        return this.rel.find('project', id)
    }

    // 调用原生pouchdb-find的示例
    nativeFind(selector: any) {
        return this.base_db.find({ selector })
    }
}

补充说明

你之前能运行的带selector的写法,实际调用的是pouchdb-find的原生查询,不会处理relational-pouch定义的实体关联映射,需要处理关联数据时必须走this.rel下的方法。


内容的提问来源于stack exchange,提问作者theSiberman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 23:09:03