【问题标题】:What is a Mongoose model property that contains 'ref' but does not specify type?什么是包含“ref”但未指定类型的 Mongoose 模型属性?
【发布时间】:2018-01-07 07:32:40
【问题描述】:

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

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

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

但是在我正在审查的代码中(不是我写的)有很多这种类型的属性

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

引用了另一个模式,但没有类型。这是同一种关系吗?暗示id?这是子文档吗?

另外一个问题:如果在模型中我想引用链接模型(或模式)的属性,我需要先populate 吗?也就是说,如果它是一个子文档,我可以使用点符号,但如果它是一个“链接”文档,我不确定。

【问题讨论】:

  • 没有类型会抛出错误 TypeError: Undefined type Source at source.ref。似乎是无效的架构定义。你能运行代码来创建文档吗?​​
  • 是的——这是我作为初级开发人员在编写了大量代码后加入的一个大型项目。我相信我看到了我的方式的错误,因为所有这些模式都被传递给模型“工厂”,该模型“工厂”设置了 os objectID 类型,我认为它可以解决所有问题——我应该在代码中进一步阅读.
  • 因此,在模型工厂中我们有如下代码sn -p:
  • new: function(name, properties, statics, methods, schemaMods) { // 将默认定义添加到具有引用的属性并加载引用模式 Object.keys(properties).forEach(function(key) { var modifiedProperty = (property) => { if (property.ref) { property.autopopulate = true; property.type = mongoose.Schema.Types.ObjectId; } return property; };

标签: node.js mongodb mongoose


【解决方案1】:

答案是模型模式不是独立存在的,而是传递给模型“工厂”,从而为它们提供所需的属性类型。

因此来自该工厂的以下sn-p(下)。我查看了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]);
  }
});

【讨论】:

    猜你喜欢
    • 2018-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    • 2019-09-05
    • 2022-07-21
    • 1970-01-01
    相关资源
    最近更新 更多