【问题标题】:How to create a dynamic Reference in node js mongodb如何在节点 js mongodb 中创建动态引用
【发布时间】:2017-07-14 10:58:14
【问题描述】:

我正在开发一个 nodejs 程序,但我遇到了一个问题,我有一个 mongo 模式,它是一个对象列表:

players: [{
    type: Schema.Types.ObjectId,
    ref: 'User'
  }]

但是这个 ref: 'User' 不足以满足我的需要。例如,这个“玩家”有可能收到对象“用户”或对象“团队”。但是我该如何声明呢?我应该删除“ref”参数吗?

一个信息是:如果我在这个玩家属性上放一个“用户”,我不会放任何其他类型,所有对象都是用户,“团队”也是如此。但我会在创建对象时知道是团队列表还是用户列表。

那么我该如何声明呢?

谢谢

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:
        const documentSchema = new Schema({
          referencedAttributeId: {
            type: Schema.Types.ObjectId,
            refPath: 'onModel'
           },
          onModel: {
            type: String,
            required: true,
            enum: ['Collection1', 'Collection2']
          }
        });
    

    现在此集合具有名为 referencedAttributeId 的属性,该属性链接到两个集合('Collection1'、'Collection2')。每当你使用 .populate() 函数时,mongoose 都会自动获取引用的数据。

    const data = await CollectionName.find().populate('referencedAttributeId','attributeName1 attributeName2')
    

    【讨论】:

      【解决方案2】:

      Mongoose 支持dynamic references。您可以使用StringrefPath 指定类型。看一下documentation提供的schema示例:

      var userSchema = new Schema({
        name: String,
        connections: [{
          kind: String,
          item: { type: ObjectId, refPath: 'connections.kind' }
        }]
      });
      

      上面的 refPath 属性意味着 mongoose 会查看 connections.kind 路径,用于确定用于 populate() 的模型。 换句话说, refPath 属性使您能够使 ref 属性动态。

      来自documentation 的示例,来自populate 调用:

      // Say we have one organization:
      // `{ _id: ObjectId('000000000000000000000001'), name: "Guns N' Roses", kind: 'Band' }`
      // And two users:
      // {
      //   _id: ObjectId('000000000000000000000002')
      //   name: 'Axl Rose',
      //   connections: [
      //     { kind: 'User', item: ObjectId('000000000000000000000003') },
      //     { kind: 'Organization', item: ObjectId('000000000000000000000001') }
      //   ]
      // },
      // {
      //   _id: ObjectId('000000000000000000000003')
      //   name: 'Slash',
      //   connections: []
      // }
      
      User.
        findOne({ name: 'Axl Rose' }).
        populate('connections.item').
        exec(function(error, doc) {
          // doc.connections[0].item is a User doc
          // doc.connections[1].item is an Organization doc
        });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-08-02
        • 2020-11-21
        • 1970-01-01
        • 2020-11-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-30
        相关资源
        最近更新 更多