Closed yasuto2002 closed 1 year ago
filter := bson.D{{"_id", memo.Id}}
update := bson.M{"$set": bson.M{ "text": memo.Text, "x": memo.X, "y": memo.Y, }} if result, err := memos.UpdateOne(context.Background(), filter, updated); err != nil { log.Printf("Error insert Memo: %v", err) } else { fmt.Println(result) }
> https://www.mongodb.com/docs/drivers/go/current/usage-examples/updateOne/
### アップデートされない
<img width="1168" alt="スクリーンショット 2023-01-20 10 12 48" src="https://user-images.githubusercontent.com/77332271/213596923-6cb09d93-93f9-4093-8cfb-fb6c01294769.png">
### _idが一致しなかったら新規で追加するように
```go
filter := bson.D{{"_id", memo.id}}
updated := bson.D{{"$set", bson.D{
{"text", memo.Text},
{"x", memo.X},
{"y", memo.Y},
}}}
opts := options.Update().SetUpsert(true)
if result, err := memos.UpdateOne(context.Background(), filter, updated, opts); err != nil {
log.Printf("Error insert Memo: %v", err)
} else {
fmt.Println(result)
}
https://www.mongodb.com/docs/drivers/go/current/fundamentals/crud/write-operations/upsert/
id, err := primitive.ObjectIDFromHex(memo.Id)
...
filter := bson.D{{"_id", id}}
https://www.mongodb.com/docs/drivers/go/current/usage-examples/updateOne/
保存する手順