猫鼬-引用子文档的ObjectId

猫鼬-引用子文档的ObjectId

问题描述:

ModelA 中的ObjectId是否可以引用子文档 在 modelB 中?

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

是可以的,但是您有一些选择.

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

选项1:C作为子文档

如果您确实要使用子文档,则无需创建单独的模型.您需要更改对"c"数组的引用.

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

选项2:以C作为模型

(我仅将此作为替代方法-因为您的示例似乎多余,因为您将"C"创建为单独的模型以及子文档)

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


要点

是可能的,但是您需要选择是否要将C作为模型或子文档.

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