猫鼬和 ref UUID 数组不转换

Mongoose and array of ref UUID's does not convert

当使用库 mongoose-uuid 时,我可以为我的模式设置 UUID 类型,所以当我读取数据时它是字符串 (utf-8) 格式,当我保存数据时它是 UUID ObjectID BSON 类型 4 格式。这适用于我的架构中的顶级或平面直接值和引用定义。但是,当我在架构中的引用数组中有一个 UUID 时,该数组会正确保存到数据库中,但是当它出现时,它是原始类型。根据下面的示例,您可以看到 scope_id 以正确的格式显示,但权利不是。

以下是我使用的版本: 猫鼬-uuid - 2.3.0 猫鼬 - 5.5.11

我尝试通过更改 getter 和转换值来修改库 (mongoose-uuid),但是,当我这样做时,它在呈现时有效,但在保存到数据库时失败。这很可能是因为值在保存到数据库之前被转换或强制转换。

这是一个示例架构

    {
      "code": {
        "type": String,
        "required": true
      }, 
      "scope_id": {
        "type": mongoose.Types.UUID,
        "ref": "scopes"
      },
      "entitlements": [{
        "type": mongoose.Types.UUID,
        "ref": "entitlements"
      }]
    }

实际响应示例

{
    "entitlements": [
        "zMihi1BKRomM1Q41p7hgLA==",
        "ztOYL7n1RoGA6aoc0TcqoQ=="
    ],
    "code": "APPUSR",
    "scope_id": "b8f80c82-8325-4ffd-bfd7-e373a90e7c45",
    "id": "32e79061-e531-45ad-b934-56811e2ad713"
}

预期响应

{
    "entitlements": [
        "ccc8a18b-504a-4689-8cd5-0e35a7b8602c",
        "ced3982f-b9f5-4681-80e9-aa1cd1372aa1"
    ],
    "code": "APPUSR",
    "scope_id": "b8f80c82-8325-4ffd-bfd7-e373a90e7c45",
    "id": "32e79061-e531-45ad-b934-56811e2ad713"
}

根据我的观察,如果您在 mongoose 中更改以下函数,它可以正常工作

SchemaUUID.prototype.cast = function (value, doc, init) {
  console.log("cast", value, doc, init)

  if (value instanceof mongoose.Types.Buffer.Binary) {
    if (init) {
      return getter(value);
    } else {
      return value;
    }
  }

  if (typeof value === 'string') {
    var uuidBuffer = new mongoose.Types.Buffer(uuidParse.parse(value));

    uuidBuffer.subtype(bson.Binary.SUBTYPE_UUID);

    return uuidBuffer.toObject();
  }

  throw new Error('Could not cast ' + value + ' to UUID.');
};

基本上当您保存对象时 initfalse 并且当它启动时 inittrue

如上所述,代码确实有效,但破坏了代码的另一部分。我找到了解决此问题的解决方案:

对上面的代码稍作修改

SchemaUUID.prototype.cast = function (value, doc, init) {

console.log("cast", value, doc, init)

  if (value instanceof mongoose.Types.Buffer.Binary) {
    if (init && doc instanceof mongoose.Types.Embedded) {
      return getter(value);
    }
    return value;
  }

  if (typeof value === 'string') {
    var uuidBuffer = new mongoose.Types.Buffer(uuidParse.parse(value));

    uuidBuffer.subtype(bson.Binary.SUBTYPE_UUID);

    return uuidBuffer.toObject();
  }

  throw new Error('Could not cast ' + value + ' to UUID.');
};

此替代版本的代码允许应用 POST 和 PATCH 等更新。