【问题标题】:Many to many relationship keyed by string using mongoose on node.js在 node.js 上使用 mongoose 以字符串为键的多对多关系
【发布时间】:2013-01-17 22:56:08
【问题描述】:

描述我所追求的最佳方式是从一个简化的演示 page 文档开始:

{
    name: "Page Name"
    blocks: {
        "top-content": 50f0ded99561a3b211000001,
        "bottom-content": 50f0ded99561a3b211000002
    }
}

有没有办法可以定义这种与猫鼬的多对多关系,以便我可以通过top-contentbottom-content 等字符串键查找它们?与此等效的关系类似于在多对多连接表中包含一个字符串。

重要:

  • 我不想嵌入我正在引用的块,因为它们可能被多个页面引用。

【问题讨论】:

    标签: node.js mongodb reference many-to-many mongoose


    【解决方案1】:

    Mongoose 的 query population 功能支持这一点,但 top-contentbottom-content 需要是 ObjectIds 而不是字符串(无论如何这更有效)。

    【讨论】:

    • 我想用字符串来命名它们,这就是我使用对象 ID 作为值而不是键的原因。它仍然适用于指向对象 ID 的字符串吗?架构定义是什么样的?
    • 有了猫鼬的演员阵容,我想top-content: {type: String, ref: 'Content'} 可能可以工作,但我从未尝试过。
    • 嗯,这可能不太正确 - 我想使用它的 ID 引用“内容”,我只是想键入关联。
    • mongoose 可以填充 ObjectId、Number、String 和 Buffer 类型的 _id
    【解决方案2】:

    在 Freenode 上的#node.js 中聊天后,似乎我可以将其设置为一个数组并放置包含我想要的引用的任意键/值对。

    到那时,我将自己取消引用。

    { //PAGE 1
      name:"Sticks",
      blocks:[
        "top":[OID(5),OID(6)],
        "bottom":[OID(7),OID(8)]
      ]
    };
    { //PAGE 2
      name:"Poopsicles",
      blocks:[top:[OID(7)]]
    };
    
    //BLOCKS
    {
      OID:5,
      name:"top"
    };
    {
      OID:7,
      name:"bottom rocker"
    };
    
    //QUERYING
    page.findOne({name:"Sticks"}, function(e,d) {
      var a = [];
      for(l in d.blocks) {
        a.append(d.blocks[l]);
      }
      blocks.find({oid:a},function (e,b) {
        //do your stuff with the blocks and page here;
      });
    });
    

    【讨论】:

      猜你喜欢
      • 2017-04-14
      • 1970-01-01
      • 2019-08-11
      • 2015-12-06
      • 2014-01-21
      • 2014-08-15
      • 1970-01-01
      • 2017-10-07
      • 2020-06-12
      相关资源
      最近更新 更多