我正在尝试向Mongo的MongoCollection
和FindIterable
类添加一些Groovy-er方法。
如果我通过ExpandoMetaClass
添加方法,则效果很好:
// add convenience methods to MongoCollection, and FindIterable to make it more groovy friendly.
// Usage: `collection.find(partnerId: 2).each { ... }`
// or: `collection.find([partnerId: 2]).each { ... }`
MongoCollection.metaClass.find << { Map filter ->
return find((Bson) new Document(filter))
}
// Usage: `collection.find().projection(_id: 0, Rid: 1, DeliveryPartnerId: 1).each { ... }`
FindIterable.metaClass.projection << { Map fields ->
return projection((Bson) new Document(fields))
}
但是,当我尝试通过Expansion Module添加方法时:
/**
* Adds Groovy Map friendly extension methods to MongoCollection and FindIterable.
*/
class GroovyMongoExtensions {
/**
* Makes it easy to call the find method on a MongoCollection with a Map, or Map parameters.
* Example:
* <pre>collection.find(group: 10).each { ... }</pre>
* or:
* <pre>collection.find([group: 10]).each { ... }</pre>
*/
static FindIterable find(MongoCollection self, Map filter) {
return self.find((Bson) new Document(filter))
}
/**
* Makes it easy to call the projection method on a FindIterable with a Map, or Map parameters.
* Example:
* <pre>collection.find().projection(myId: 1, name: 1).each { ... }</pre>
*/
static FindIterable projection(FindIterable self, Map fields) {
return self.projection((Bson) new Document(fields))
}
}
我收到此错误:
Exception in thread "main" groovy.lang.GroovyRuntimeException: Ambiguous method overloading for method com.mongodb.client.internal.MongoCollectionImpl#find.
Cannot resolve which method to invoke for [class org.bson.Document] due to overlapping prototypes between:
[interface org.bson.conversions.Bson]
[interface java.util.Map]
我确实从ExpandoMetaClass
方法中得到了错误,但是在这种情况下,将显式强制转换添加到(Bson)
即可解决此问题。