mongoose - ObjectId that references a Sub-Document

寵の児 提交于 2019-12-18 11:59:12

问题


Would it be possible for an ObjectId in ModelA to reference a sub-document 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);  

回答1:


Yes it is possible, but you have a few options.


Option 1: C as a Subdocument

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

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 only present this as an alternative - since your example seems redundant 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 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 may want to 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' }); 

The Point

Yes its possible, but you need to pick if you want C as a model or subdocument.



来源:https://stackoverflow.com/questions/24853383/mongoose-objectid-that-references-a-sub-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!