【发布时间】:2017-05-23 07:48:00
【问题描述】:
问题:
如何根据对象中的特定键更新列表中的对象?
说明:
假设我的 mongodb 中有以下对象:
{
"keysteps":[
{"timecode":"01:00:00", "title": "Chapter 1"}
]
}
说我想用一个关键步骤列表(又名:“章节”)更新“关键步骤”,我将如何确保如果时间码已经存在,我会更新对象而不是创建一个新的一个?
如果我用这些关键步骤更新我的 mongodb:
{
"keysteps":[
{"timecode":"01:00:00", "title": "Chapter 1 - edited"}
]
}
这是我得到的输出:
keysteps": [
{
"timecode": "01:00:00",
"title": "Chapter 1"
},
{
"timecode": "01:00:00",
"title": "Chapter 1 - edited"
}
]
它没有更新 keysteps,而是在 keysteps 列表中添加了一个新对象。 如果我发送了相同的时间码对象(相同的时间码和标题),它就不会创建一个新对象。
我做了什么:
这是我用来更新的 Symfony 控制器的 sn-p:
class VideoToolsController extends Controller
{
//More code
public function keystepsUpdateAction(Request $request, int $video_id){
//If the video id already exists, throw an error
$keystepsS = $this->get('video_tools.keysteps');
$exists = $keystepsS->exists($video_id);
//Return immediately if keysteps doesn't exist.
if(!$exists)
return JsonResponseService::getErrorBadRequest("Keystep does not exist.");
$keysteps = json_decode($request->getContent(), true);
//die(var_dump($data));
$form = $this->createForm(KeystepsType::class);
$form->submit($keysteps);
//return new JsonResponse($data);
//Return bad request if the form is not valid.
if(!$form->isValid())
return JsonResponseService::getErrorBadRequest("Keysteps are not valid, try again.");
try {
$res = $keystepsS->update($video_id, $keysteps['keysteps']);
return JsonResponseService::getSuccess($res, "Updated keysteps.");
} catch(Exception $exception){
return JsonResponseService::getErrorBadRequest($exception->getMessage(), $keysteps);
}
}
//More code
}
这是我用来更新的 Php 服务中的一个 sn-p:
class KeystepsService {
//More code
//TODO: Make timecode UNIQUE
public function update($video_id, $keysteps) : int {
$updatedOne = $this->mongoCollection->updateOne(
['video_id' => $video_id ],
['$addToSet' => [ "keysteps" => [ '$each' => $keysteps ]]]
);
return $updatedOne->getModifiedCount();
}
//More code
}
mongodb/mongo-php-库:
请随意给我一些关于如何措辞标题/问题的建议,我觉得好像这不是重点。
【问题讨论】:
标签: php json mongodb symfony mongodb-php