2014-08-29 34 views
0

我想用mongoose定義一個mongo模式。我需要創建一個引用用戶的'Event Schema'。所以我用用戶Schema的引用ObjectId填充'users'字段。不過,我還需要在該用戶屬性上添加一些特定於該事件的額外字段。因此,如下所示:在引用另一個模式加上額外字段的mongo模式中定義一個屬性

var mongoose = require('mongoose'); 
var Schema = mongoose.Schema; 

var EventSchema = new Schema({ 

    name: String, 
    date: Date, 
    users: [{ 
     profile: { 
      type: Schema.ObjectId, 
      ref: 'User' 
     }, 
     RankNumber: Number, 
     bibNumber: Number 
    }], 
    published: Boolean 

}); 

mongoose.model('Event', EventSchema); 

但這不起作用。我不確定最好的方式去做我想要達到的目標。

所以,如果我有一個構造函數,例如:

function User(bib, rank, profile) { 
    this.bib = bib; 
    this.rank = rank; 
    this.profile = profile; 
} 

,然後我調用構造函數並傳遞一個用戶ID爲配置文件屬性,MongoDB的將創建一個新的ID字段。我得到一個像這樣的JSON響應:

{ 
    "name": "Event name", 
    "_id: "mongoid", 
    "users": [ 
     { 
      "bibNumber": "278", 
      "rankNumber": "21", 
      "profile": "users mongo _id number", 
      "_id": "a new mongo _id" 
     } 
    ] 
} 

我需要填充配置文件字段。但是,下面的不會起作用:。

Event.find()填充( '用戶')執行(函數(ERR,事件){....

+0

「這行不通」請精確 – Vinz243 2014-08-29 09:38:53

+0

我已經編輯了問題,見上面 – StujayH 2014-08-29 10:42:36

+0

你可以嘗試'填充(「users.profile」)' – Vinz243 2014-08-29 10:48:43

回答

0

你必須使用,就像我說的在註釋:

Event.find(...).populate('users.profile').exec(...); 
相關問題