javascript - 试图让我的函数能够拥有动态选择器,这样我就不必重复自己了
问题描述
这是我的代码,我发现自己必须为解析 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 对象,使对象上的选择器是动态的......
我使用 ${} 因为这就是我动态构建字符串的方式,但不能这样做或使它适用于函数或命名,例如,我不能创建一个字符串变量并将该名称用作函数或其方法的名称,但是这正是我想要做的。再次感谢任何能够提供帮助的人。
提前致谢。
解决方案
好吧,我会用一行来做到这一点,不需要将它包装在一个函数中
await db.Pet.updateOne({ _id: petId }, { $push: : { petImages : {'fileName':fileName}}, updated: Date.now() });
推荐阅读
- python - 遍历 Pandas 中的 DateTimeIndex
- c++ - C++ Primer 第 5 版,练习 1.23 无输出
- c# - 从 SreamingAssets 文件夹中读取 json 文件
- css - 设置行高且行间出现间距时扩展包裹跨度的背景颜色
- c# - 使用包含“/”的字符串序列化对象时出现问题
- laravel - 如何让 Laravel Echo 投入生产?
- java - 字典输入文件和字符串操作
- javascript - JavaScript:3 个单选按钮,第 3 个有下拉菜单,当任何一个被选中时有提交按钮,然后给出消息
- javascript - fetch/axios async/await request freeze app in react native
- html - 为什么我不能翻译图像?