mongodb 具有不同键名的JSON文件

avkwfej4  于 2022-11-22  发布在  Go
关注(0)|答案(1)|浏览(118)

我正在使用mongoDb和mongoose libraray。我的模式是英语的,但是我收到了一个带有德语(或其他)关键字的相同结构。
MongoDB模式:

{
  "Uid": Number,
  "User": {
    "Firstname": String,
    "Lastname": String
  }
}

JSON对象:

"Uid": Number,
"Benutzer": {
  "Vorname": String,
  "Nachname": String
}

我以字符串的形式接收JSON对象,并使用JSON.parse,realObject更复杂,我不想一个字段一个字段地复制。如果关键字相同,我可以使用一个简单的赋值:

const my_object = JSON.parse(file_as_string)
MyObject.findOneAndUpdate(
  { UID: my_object.Uid},
  {
    User: my_object.Benutzer
  })

我的问题是:我如何将JSON(包含德语关键字)转换为包含英语关键字的模式?

4c8rllxm

4c8rllxm1#

您可能需要深度克隆对象并在此过程中转换属性名称。

let translations = { 
      "Benutzer": "User", 
      "Vorname": "Firstname", 
      "Nachname": "Lastname", 
      "Strasze": "Street",
      "PLZ": "ZIP",
      "Ort": "City",
      "Nummer": "Number"
}

function deepClone(data) {
  //For arrays deepclone every element in the array  
  if (Array.isArray(data)) {
    return data.map(d => deepClone(d));
  }

  //For object deepclone every property and translate the property's name
  //Fallback on the original name, if no translation is found
  if (typeof data === "object") {
    let result = {}
    for (let key in data) {
      result[translations[key]||key] = deepClone(data[key]);
    }
    return result;
  }

  //return primitive datatypes (number, string, bool) as they are
  return data;
}
    
let g = { 
  Uid: 1, //this one is not gonna be translated because there is no translation entry
  Benutzer: { 
    Vorname: "Papa", 
    Nachname: "Schlumpf", 
    Adressen: [  //this one is not gonna be translated because there is no translation entry
      { Strasze: "Hauptstraße", Nummer: 1, PLZ: "1234", Ort: "Schlumpfhausen" },
      { Strasze: "Hauptplatz", Nummer: 17, PLZ: "1235", Ort: "Gargamelsdorf" }
    ]
  }
};

console.log(deepClone(g));

相关问题