how to filter field golang mongodb update logic

Viewed 41
func checkCondition(p Product) bson.D {
    var setElements bson.D
    if len(p.ModelName) > 0 {
        setElements = append(setElements, bson.E{Key: "modelName", Value: p.ModelName})
    }
    if len(p.Category) > 0 {
        setElements = append(setElements, bson.E{Key: "category", Value: p.Category})
    }
    if len(p.Color) > 0 {
        setElements = append(setElements, bson.E{Key: "color", Value: p.Color})
    }
    if len(p.Description) > 0 {
        setElements = append(setElements, bson.E{Key: "description", Value: p.Description})
    }
    if len(p.ImgUrl) > 0 {
        setElements = append(setElements, bson.E{Key: "imgurl", Value: p.ImgUrl})
    }
    if len(p.Material) > 0 {
        setElements = append(setElements, bson.E{Key: "material", Value: p.Material})
    }
    if len(p.ProductName) > 0 {
        setElements = append(setElements, bson.E{Key: "productname", Value: p.ProductName})
    }
    

    return setElements
}

my code here

I wonder if it is right to check all the data.

I think there's a better way. I'm not used to using MongoDB for Go Can you suggest a better way for me?

0 Answers
Related