首页 > 解决方案 > 试图让我的函数能够拥有动态选择器,这样我就不必重复自己了

问题描述

这是我的代码,我发现自己必须为解析 json 或制作函数做很多事情。

// Adder Functions... hate repeating myself
async function addPetImagesToPet(petId, fileName) {
  const pet = await db.Pet.findById(petId);
  await pet.petImages.push({'fileName':fileName});
  pet.updated = Date.now();
  await pet.save();
  //console.log(pet);
}

async function addPropertyImagesToProperty(propertyId, fileName) {
  const property = await db.Property.findById(propertyId);
  await property.propertyImages.push({'fileName':fileName});
  property.updated = Date.now();
  await property.save();
  //console.log(property);
}

async function addAccountImagesToAccount(accountId, fileName) {
  const account = await db.Account.findById(accountId);
  await account.accountImages.push({'fileName':fileName});
  account.updated = Date.now();
  await account.save();
  //console.log(account);
}

//how can I do `await db.${my_type/Object_Name!!! <--this is what im asking about}.findById(this obviously can be a var np)

我发现自己在我的大部分服务中重复了很多次,我试图在我的大部分服务前端和后端进一步扩展它。如果我知道如何做到这一点,我实际上可以为每种对象类型的大多数用例提供一个“CRUD”服务。

来了很多,一直让我疯狂解析 JSON 对象,使对象上的选择器是动态的......

我使用 ${} 因为这就是我动态构建字符串的方式,但不能这样做或使它适用于函数或命名,例如,我不能创建一个字符串变量并将该名称用作函数或其方法的名称,但是这正是我想要做的。再次感谢任何能够提供帮助的人。

提前致谢。

标签: javascriptarraysjsonmongodbtypescript

解决方案


好吧,我会用一行来做到这一点,不需要将它包装在一个函数中

await db.Pet.updateOne({ _id: petId }, { $push: : { petImages : {'fileName':fileName}}, updated: Date.now() });

推荐阅读