【问题标题】:Mongoose Map of Map, is not working for me地图的猫鼬地图,对我不起作用
【发布时间】:2021-04-07 03:37:28
【问题描述】:

我有一个 Mongoose 模型,它应该存储 Objects of Objects。

这是我要存储的元素示例:

    var company = new Company({
      documents : {
                    "outerKey1": {"innerKey1": {name:"xxx"}, "innerKey2": {name:"yyy"}},
                    "outerKey2": {"innerKey1": {name:"xxx"}}
                  }
    })

所以我将模型定义如下:

    var InnerMapSchema = new Schema({
     type : Map,
     of : {
             name:   {type:String}
          }
    });


    var OuterMapSchema = new Schema({
       type : Map,
       of : InnerMapSchema,
       default:{}
      });

    var CompanySchema = new Schema({
         documents: {type: OuterMapSchema}
    });

反正它不工作,我一个文件都保存不了。

function save_MapElement(company_id, inner_key, outer_key, name)
{
  var company = Company.findById(company_id); // it's async in reality
  if(!company.documents) { company.documents = {}; }
  if(!company.documents.get(outer_key) { company.documents.set(outer_key, {}); }

   company.documents.get(outer_key).set(inner_key, {"name":name});
   company.save();
}

我在尝试使用 .set() 时收到 TypeError: Cannot read property 'set' of undefined。 为什么?它是如何工作的?

$ npm mongoose --version
$ 6.4.1

【问题讨论】:

    标签: mongoose mongoose-schema


    【解决方案1】:

    如果 company.documents 尚不存在,则需要将其初始化为猫鼬 Map 对象。在我的代码中,我通过向我的模式添加一个方法来解决这个问题,每当我需要在一个还没有它的文档上创建地图时,我都会调用该方法:

    presentationProgress: {
        type: Map,
        of: {
            highestDecimalCompletion: Number,
            longestTimeDwelled: Number
        }
    }
    ...
    userSchema.methods.initializePresentationProgressMap = function() {
        this.presentationProgress = new Map();
    }
    

    就您而言,我认为您只需将company.documents = {} 更新为company.documents = new Map() 并将.set(outer_key, {}) 更新为.set(outer_key, new Map()。正如您的代码使用的那样,我没有尝试使用嵌套地图,但我认为它应该可以工作。我知道如果你不调用 Map() 构造函数,它是行不通的。

    【讨论】:

    • 谢谢你的回答。我解决了使用Schema.Types.Mixed,而不是使用obj.markModified('field_name')。无论如何,我下次会尝试您的解决方案。
    猜你喜欢
    • 2015-03-27
    • 2018-07-31
    • 2018-03-03
    • 1970-01-01
    • 2019-01-16
    • 2019-10-17
    • 2016-05-17
    • 2021-09-25
    • 1970-01-01
    相关资源
    最近更新 更多