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

Let's say I have two mongoose schemes:

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

Is there any way to add AccountSchema to AgentSchema without its collection?

+5
source share
1 answer

It doesn't seem like it's possible. These two solutions are designed to either use DocumentId or virtual:

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

All Articles