I'm making a query on the basis of the conditions but there is a error in the appending of them the query I'm making is:-
query := bson.M{}
query["$or"] = []bson.M{}
if keyword != "" {
query["$or"] = append(query["$or"], bson.M{"author": bson.RegEx{"(?i).*" + keyword + ".*", "i"}})
query["$or"] = append(query["$or"], bson.M{"title": bson.RegEx{"(?i).*" + keyword + ".*", "i"}})
}
if types == "" {
query["$or"] = append(query["$or"], bson.M{"type": bson.RegEx{"(?i).*" + types + ".*", "i"}})
}
if category == "" {
query["$or"] = append(query["$or"], bson.M{"category": bson.RegEx{"(?i).*" + category + ".*", "i"}})
}
if tag == "" {
query["$or"] = append(query["$or"], bson.M{"tags": bson.RegEx{"(?i).*" + tag + ".*", "i"}})
}
if len(ids) > 0 {
query["_id"] = bson.M{"$in": ids}
}
There is problem of appending the data with the query["$or"]
. The error comes out is:-
first argument to append must be slice; have interface {}
first argument to append must be slice; have interface {}
first argument to append must be slice; have interface {}
first argument to append must be slice; have interface {}
first argument to append must be slice; have interface {}
Can anyone tell me that how will I solve this problem.
Right now you're passing an interface{}
, as you can see from the definition of bson.M. So you need to assert that to some type of slice.
You're assigning a slice of type []bson.M
to the value earlier, so just assert that type. Example:
query["$or"] = append(query["$or"].([]bson.M), bson.M{"author": bson.RegEx{"(?i).*" + keyword + ".*", "i"}})
what would probably be more readable, though, is to assign your calculated value at the end instead:
or := []bson.M{}
// ...
or = append(or, ...)
query["$or"] = or