如何在Mongoose中为现有模式定义嵌套对象?

时间:2011-10-12 17:48:13

标签: node.js mongoose

假设我有两个mongoose模式:

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

无论如何都要将AccountSchema添加到AgentSchema而不是集合吗?

1 个答案:

答案 0 :(得分: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(); });