yasuto2002 / SyncMemo

0 stars 0 forks source link

ボードを保存する #51

Closed yasuto2002 closed 1 year ago

yasuto2002 commented 1 year ago

保存する手順

  1. websocketで送られてきた値をchanelに保存
  2. goroutineでredisに保存していく
  3. websocketの接続が切れたらmongoに保存
yasuto2002 commented 1 year ago

値がアップデートできない

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/