你如何定义一个嵌套对象到Mongoose中的现有模式?

假设我有两个mongoose模式:

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

无论如何,将帐户模式添加到AgentSchema而不是集合?

它看起来不可能。 这两个解决scheme是使用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} }) 

虚函数:

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