Mongoose - ObjectId that references a subdocument

Can an ObjectId in ModelA refer to a subdocument in modelB ?

var C = new Schema({...}); var B = new Schema({c: [C]}); var A = new Schema({c: { type: ObjectId, ref: 'ModelB.ModelC' }); var Model_A = mongoose.model('ModelA', A); var Model_B = mongoose.model('ModelB', B); var Model_C = mongoose.model('ModelC', C); 
+7
mongodb mongoose subdocument
source share
1 answer

Yes, it is possible, but you have several options.


Option 1: C as a subdocument

If you really want to use subdocuments, you do not need to create a separate model. You need to change the reference to the array 'c'.

 var C = new Schema({...}); var B = new Schema({c: [C]}); var A = new Schema({c: { type: ObjectId, ref: 'ModelB.c' }); var Model_A = mongoose.model('ModelA', A); var Model_B = mongoose.model('ModelB', B); 

Option 2: C as a model

(I present this only as an alternative, since your example seems superfluous, since you create "C" as a separate model, as well as a subdocument)

Alternatively, it may make sense to have separate collections; you can create a mongoose model for each. Each of them will be a separate collection:

 var Model_A = mongoose.model('ModelA', A); var Model_B = mongoose.model('ModelB', B); var Model_C = mongoose.model('ModelC', C); 

In this case, you can directly reference each model:

 var C = new Schema({...}); var B = new Schema({c: { type: ObjectId, ref: 'ModelC' }}); var A = new Schema({c: { type: ObjectId, ref: 'ModelC' }); 

Dot

Yes, it is possible, but you need to choose whether you want C as a model or subdocument.

+14
source share

All Articles