私はupdateOne
、findOneAndUpdate
からinsert
まで多くの方法を試みましたし、bulkWrite
でも成功しませんでした。
私が行ったことは、ユーザーコレクションとimage_uploadコレクションの2つのコレクションがあることです。私はユーザーがアップロードした他のすべての画像の横に、ユーザーのプロフィール画像をimage_uploadの中に保存します。
私がユーザーコレクションに保存するのは、ユーザーがアカウントを作成しているときにアップロードしたイメージと一致するimage_uploadコレクションのObjectIDです(プロファイルの編集を通じていつでも新しいプロファイルイメージをアップロードできます)。
私が望むのは、ObjectIdを更新する機能です。
フィールドpersonal.profile_id
は配列である必要がありますが、ドキュメント内ではobjectId型です。ここにコードがあります。理想的には、文字列だけでなく、ObjectIDを持つことが理想です。
$db = static::db()->image_upload;
try {
$newdata = [
"data"=>
[
"url" => $publlic_url,
"type"=> $mimetype,
"date"=>new MongoDB\BSON\UTCDateTime(),
"profile_pic" => true
],
"uid"=>New MongoDB\BSON\ObjectId($uid)
];
$oauth_update = $db->insertOne($newdata);
$view['newdata'] = $newdata;
} catch(MongoResultException $e) {
return $response->withStatus(200)
->withHeader('Content-Type', 'application/json')
->write($e->getDocument());
}
$ids = $oauth_update->getInsertedId();
$latest = $db->findOne(array("uid"=>New MongoDB\BSON\ObjectId($uid)));
// Check first, last and other personal details.
$db = static::db()->users;
try {
$newdata = ['$set' =>["personal.profile_id"=>New MongoDB\BSON\ObjectId($ids)]];
$member_profile = $db->findOneAndUpdate(
['kst'=>New MongoDB\BSON\ObjectId($uid)],
['$push' =>["personal.profile_id"=>['$oid'=>New MongoDB\BSON\ObjectId($ids)]]],
[
'projection' =>
[ 'personal' => 1 ],
"returnDocument" => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER
]);
} catch(MongoResultException $e) {
echo $e->getCode(), " : ", $e->getMessage(), "\n";
var_dump($e->getDocument());
return $response->withStatus(200)
->withHeader('Content-Type', 'application/json')
->write(array('code'=>$e->getCode(), 'message'=>$e->getMessage));
}
return $response->withStatus(200)
->withHeader('Content-Type', 'application/json')
->write(json_encode($member_profile));
にですあなたが実際にここで尋ねていることは少し不明です。しかし、 '$ ids = $ oauth_update-> getInsertedId()'と表示される方法は、実際には 'ObjectId'を返さなければならないので、再度値をキャストする必要はありません。ですから、代わりに '['$ push' => [" personal.profile_id "=> $ ids]]'を使うべきです。また、 "複数"の命名は、単なる値でなければならないときには本当に明確ではありません。そして、 "配列をプッシュする"ためには、それが意図の場合は、['$ each'](https://docs.mongodb.com/manual/reference/operator/update/each/)修飾子を使用します。 –