什么是包含'ref'但不指定类型的猫鼬模型属性?



对猫鼬来说非常陌生 - 我正在处理一个现有的项目,并被赋予了更改一些模型属性的任务。 我了解如果模型包含这种类型的属性

postedBy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}

此属性引用另一个模型/架构,若要访问该链接模型/架构,需要populate它才能访问此属性。

但是在我正在审查的代码(我没有写(中,有许多这种类型的属性

contentTypes: [{ ref: 'ContentType' }],
source: { ref: 'Source',required: true },

其中引用了另一个架构,但没有类型。 这是同一种关系,隐含着id吗?这是子文档吗?

作为一个附加问题:如果在模型中我想引用链接模型(或模式(的属性,我是否需要先populate? 也就是说,如果它是一个子文档,我只能使用点符号,但如果它是一个"链接"文档,我不确定。

答案是模型架构不会独立存在,而是传递给模型"工厂",这为它们提供了所需的属性类型。

因此,来自该工厂的以下代码片段(如下(。 我查看了mongoose-autopopulate的文档,但我不明白autopopulate=true是什么意思。

new: function(name, properties, statics, methods, schemaMods) {
// Add default definition to properties with references and load reference schemas
Object.keys(properties).forEach(function(key) {
var modifiedProperty = (property) => {
if (property.ref) {
property.autopopulate = true;
property.type = mongoose.Schema.Types.ObjectId;
}
return property;
};
if (Array.isArray(properties[key]) && properties[key].length === 1) {
properties[key][0] = modifiedProperty(properties[key][0]);
} else {
properties[key] = modifiedProperty(properties[key]);
}
});

最新更新