2011-10-12 28 views
5

說我有兩個貓鼬模式:如何定義一個嵌套對象到Mongoose中的現有模式?

var AccountSchema = new Schema({ 
     userName: String 
    , password: String 
}) 
var AgentSchema = new Schema({ 
    Name : String 
    , Account: AccountSchema 
}) 

反正是有AccountSchema添加到沒有它是一個集合AgentSchema?

+0

的'Account'場也許應該是一個對象ID指向實際的「賬戶」對象數據。 –

回答

4

它看起來不可能。這兩種方案,其一是使用DocumentId或虛函數:

的ObjectId:

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

var AccountSchema = new Schema({ 
     userName: String 
    , password: String 
}) 
var AgentSchema = new Schema({ 
    name : String 
    , account: {type: ObjectId} 
}) 

VIRTUALS:

var AccountSchema = new Schema({ 
     userName: String 
    , password: String 
}) 
var AgentSchema = new Schema({ 
    name : String 
    , _accounts: [AccountSchema] 
}) 

AgentSchema.virtual('account') 
    .set(function(account) { this._accounts[0] = account; }) 
    .get(function() { return this._accounts.first(); }); 
相關問題