如何在Node.js中创建动态参考(MongoDB)

3

我正在开发一个Node.js程序,遇到了一个问题,我有一个MongoDB数据库的模式是对象列表:

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

但是这个参考值 'User' 对于我需要的东西不够。这些“玩家”有可能接收对象 'User' 或者对象 'Team' 例如。但是我该如何声明它呢?我应该删除 "ref" 参数吗?
一个信息是:如果我将一个 "User" 放在这些 players 属性中,我不会放入任何其他类型,所有的对象都将是用户,对于 "Team" 也是同样的事情。但是在创建对象的时候,我会知道它是团队列表还是用户列表。
那么我该如何声明它呢?
谢谢
2个回答

3
    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')

1
支持动态引用。您可以使用StringrefPath指定类型。请查看文档中提供的模式示例:
var userSchema = new Schema({
  name: String,
  connections: [{
    kind: String,
    item: { type: ObjectId, refPath: 'connections.kind' }
  }]
});

上面的refPath属性意味着mongoose将查看connections.kind路径以确定populate()要使用哪个模型。换句话说,refPath属性使您可以使ref属性动态化。
一个例子来自文档中的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
  });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接