Don Newton | 379ae25 | 2019-04-01 12:17:06 -0400 | [diff] [blame^] | 1 | // Copyright (C) MongoDB, Inc. 2017-present. |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 4 | // not use this file except in compliance with the License. You may obtain |
| 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 |
| 6 | |
| 7 | package command |
| 8 | |
| 9 | import ( |
| 10 | "errors" |
| 11 | |
| 12 | "github.com/mongodb/mongo-go-driver/bson" |
| 13 | "github.com/mongodb/mongo-go-driver/x/bsonx/bsoncore" |
| 14 | "github.com/mongodb/mongo-go-driver/x/network/result" |
| 15 | ) |
| 16 | |
| 17 | // unmarshalFindAndModifyResult turns the provided bson.Reader into a findAndModify result. |
| 18 | func unmarshalFindAndModifyResult(rdr bson.Raw) (result.FindAndModify, error) { |
| 19 | var res result.FindAndModify |
| 20 | |
| 21 | val, err := rdr.LookupErr("value") |
| 22 | switch { |
| 23 | case err == bsoncore.ErrElementNotFound: |
| 24 | return result.FindAndModify{}, errors.New("invalid response from server, no value field") |
| 25 | case err != nil: |
| 26 | return result.FindAndModify{}, err |
| 27 | } |
| 28 | |
| 29 | switch val.Type { |
| 30 | case bson.TypeNull: |
| 31 | case bson.TypeEmbeddedDocument: |
| 32 | res.Value = val.Document() |
| 33 | default: |
| 34 | return result.FindAndModify{}, errors.New("invalid response from server, 'value' field is not a document") |
| 35 | } |
| 36 | |
| 37 | if val, err := rdr.LookupErr("lastErrorObject", "updatedExisting"); err == nil { |
| 38 | b, ok := val.BooleanOK() |
| 39 | if ok { |
| 40 | res.LastErrorObject.UpdatedExisting = b |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | if val, err := rdr.LookupErr("lastErrorObject", "upserted"); err == nil { |
| 45 | oid, ok := val.ObjectIDOK() |
| 46 | if ok { |
| 47 | res.LastErrorObject.Upserted = oid |
| 48 | } |
| 49 | } |
| 50 | return res, nil |
| 51 | } |