Mongoose - 不能插入一个字典类型的子文档。

问题描述 投票:1回答:1

我的文档有一个Mongoose模式。Company,它有几个领域。其中的一个(documents_banks)是一个 "自由 "字段,是字典类型的,因为我事先不知道键的名称.问题是,当我保存文档(company.save())即使保存的文档中有新的子文档,在DB中也没有实际保存新的子文档。

var Company = new Schema({
  banks: [{ type: String }], // array of Strings
  documents_banks: {} // free field
});

即使 documents_banks 不受Schema的限制,它将有这样的结构(在我看来)。

{
  "bank_id1": {
    "doc_type1": {
      "url": { "type": "String" },
      "custom_name": { "type": "String" }
    },
    "doc_type2": {
      "url": { "type": "String" },
      "custom_name": { "type": "String" }
    }
  },
  "bank_id2": {
    "doc_type1": {
      "url": { "type": "String" },
      "custom_name": { "type": "String" }
    }
  }
}

但我并不知道键的名字 bank_id 既不 doc_type,所以我使用了字典类型(documents_banks:{}).

现在,下面这个函数是我用来在 documents_banks. 我总是用同样的逻辑来保存新的sub_docs...。 总之,这次似乎保存了,但并没有。

function addBankDocument(company_id, bank_id, doc_type, url, custom_name) {
  // retrieve the company document
  Company.findById(company_id)
    .then(function(company) {

      // create empty sub_docs if needed
      if (!company.documents_banks) {
        company.documents_banks = {};
      }
      if (!company.documents_banks[bank_id]) {
        company.documents_banks[bank_id] = {};
      }

      // add the new sub_doc
      company.documents_bank[bank_id][doc_type] = {
        "url": url,
        "custom_name": custom_name
      };
      return company.save();
    })
    .then(function(saved_company) {
      // I try to check if the new obj has been saved
      console.log(saved_company.documents_bank[bank_id][doc_type]);
      // and it actually prints the new obj!!
    });
}

saved_company 所回 .save() 实际上有新的sub_docs,但如果我检查DB,就没有新的sub_docs!我可以只保存第一个,其他的都没有保存。我可以只保存第一个,其他的都没有保存。

所以,console.log()总是打印新的sub_docs,但实际上在DataBase中,只保存了第一个sub_docs,其他的都没有。所以在最后。saved_company 总是有1个sub_doc,即第一个。

我觉得很奇怪,因为 saved_company 有新的sub_docs。会发生什么?

下面这个是真正的由DB提取的,它将永远只包含sub_docs "doc_bank@1573807781414"其他的将不存在于数据库中。

{
  "_id": "5c6eaf8efdc21500146e289c", // company_id
  "banks": [ "MPS" ],
  "documents_banks": {
    "5c5ac3e025acd98596021a9a": // bank_id
    {
      "doc_bank@1573807781414": // doc_type
      {
        "url": "http://...",
        "custom_name": "file1"
      }
    }
  }
}

版本。

$ npm -v
6.4.1

$ npm show mongoose version
5.7.11

$ node -v
v8.16.0
mongodb mongoose mongoose-schema
1个回答
0
投票

看来,由于 mongoose 不知道 subdoc 的确切模型,它无法知道它何时发生变化。所以我不得不使用 markModified 以此来通知 "自由字段"(又称字典或MixedType)的变化。

    company_doc.documents_banks["bank_id2"]["doc_type3"] = obj; // modify
    company_doc.markModified('documents_banks'); // <--- notify changes
    company_doc.save(); // save changes

据我所知, markModified 强制模型在保存()期间 "更新 "该字段。

© www.soinside.com 2019 - 2024. All rights reserved.