2017-07-14 66 views
1

我發展一個的NodeJS程序,我面臨的一個問題,我有一個蒙戈架構是對象的列表:如何創建節點JS MongoDB的動態參考

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

但這REF:「用戶'不足以滿足我的需求。例如,這個「玩家」有可能接收對象「用戶」或對象「團隊」。但我該如何申報?我應該刪除「ref」參數嗎?一個信息是:如果我把一個「用戶」放在這個玩家屬性上,我不會放任何其他類型,所有對象都會是用戶,對於「團隊」來說也是一樣的。但是我會知道在我創建對象的時候是否會列出團隊或用戶列表。

那麼我該如何申報呢?

謝謝

回答

0

Mongoose支持dynamic references。您使用StringrefPath指定類型。在由documentation提供的模式的例子來看一看:

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

的refPath屬性以上意味着貓鼬將着眼於 connections.kind路徑,以確定要用於填入哪個模型()。 換句話說,refPath屬性使您可以使ref 屬性動態。

一個例子,從documentationpopulate呼叫的:

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