Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you define a nested object to an existing schema in Mongoose?

Say I have two mongoose schemas:

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

is there anyway to add AccountSchema to the AgentSchema without it being a collection?

like image 641
Chance Avatar asked Oct 09 '22 18:10

Chance


1 Answers

It doesn't look like it's possible. The two solutions are to either use a DocumentId or virtuals:

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(); }); 
like image 163
Chance Avatar answered Oct 13 '22 10:10

Chance