2011-11-03 74 views
4

遞歸嵌入文檔基於this example(工作):貓鼬:在CoffeeScript中

var Comment = new Schema(); 

Comment.add({ 
    title : { type: String, index: true } 
    , date : Date 
    , body : String 
    , comments : [Comment] 
}); 

我想創建一個版本的CoffeeScript

mongoose = require 'mongoose' 
Schema = mongoose.Schema 

Person = new Schema 
Person.add 
    mother: Person 
    father: Person 

但是它返回一個錯誤,我不理解爲什麼

TypeError: undefined is not a function 
    at CALL_NON_FUNCTION_AS_CONSTRUCTOR (native) 
    at Function.interpretAsType (/path/node_modules/mongoose/lib/schema.js:202:10) 
    at Schema.path (/path/node_modules/mongoose/lib/schema.js:162:29) 
    at Schema.add (/path/node_modules/mongoose/lib/schema.js:110:12) 
    at Object.<anonymous> (/path/Models/test.coffee:6:10) 
    at Object.<anonymous> (/path/Models/test.coffee:10:4) 
    at Module._compile (module.js:411:26) 
    at Object.run (/usr/local/lib/node_modules/coffee-script/lib/coffee-script.js:57:25) 
    at /usr/local/lib/node_modules/coffee-script/lib/command.js:147:29 
    at /usr/local/lib/node_modules/coffee-script/lib/command.js:115:26 

編輯:好吧,我發現,它不工作時,人不是一個數組(括號內),但爲什麼?

回答

6

嵌入文檔只能作爲數組中的項存在。這是由設計,你可以問the authors其原因:)

你可能想使用一個DBRef

Person = new Schema 
    mother: { type: Schema.ObjectId, ref: 'Person' } 
    father: { type: Schema.ObjectId, ref: 'Person' } 

(注意你不需要add調用)

docs for populate/DBRef