如何在节点js mongodb中创建动态引用

时间:2017-07-14 10:58:15

标签: node.js mongodb

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

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

但是这个参考:“用户”不足以满足我的需求。例如,这些“玩家”有可能接收对象“用户”或对象“团队”。但我怎么能宣布呢?我应该删除“ref”参数吗?

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

那我怎么声明呢?

谢谢

2 个答案:

答案 0 :(得分:0)

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

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

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

来自populate的{​​{1}}来电:

的示例
// 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
  });

答案 1 :(得分:0)

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

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

const data = await CollectionName.find().populate('referencedAttributeId','attributeName1 attributeName2')
相关问题