Golang Mongodb $push and if doesn't exist create

Viewed 345

So basically I have this struct that has to appear in mongoDb and I have to write a query witch would firstly check if an object with the profileID already exists it would push a new offer id to the existing objects offers array. And if an Object with the profileID does not exist it would create one and add the offer id to the offers array. Is it possible to do it in one query? if so could anyone help me on how it could be implemented?

type IgnoreOffer struct {
    ProfileID primitive.ObjectID   `json:"profileID" bson:"profileID"`
    Offers    []primitive.ObjectID `json:"offers,omitempty" bson:"offers,omitempty"`
}

Here's my code for however it does not create a new object in the database.

func getIgnoreOffersCollection() *mongo.Collection {
    return db.GetMongoCollection("ignoreOffers")
}

func ignoreOffer(profileId primitive.ObjectID, offerId primitive.ObjectID) error {
    var offer IgnoreOffer
    offer.ProfileID = profileId
    ctx, _ := db.GetTimeoutContext()
    filter := bson.M{"profileID": profileId}
    update := bson.M{
        "$set": bson.M{
            "updatedAt": time.Now(),
        },
        "$push": bson.M{
            "offers": offerId,
        },
    }

    _, err := getIgnoreOffersCollection().UpdateOne(ctx, filter, update)
    if err != nil {
        log.Error("could not update ignoreOffer collection, err: ", err)
        return err
    }
    return nil
}
1 Answers

You need an upsert in your case:

_, err := getIgnoreOffersCollection().UpdateOne(ctx, filter, update, options.Update().SetUpsert(true))
Related