mirror of
https://github.com/tursom/TursomServer.git
synced 2025-03-04 06:40:11 +08:00
impl mongo module
This commit is contained in:
parent
fc8cd49841
commit
79ed71efae
@ -20,6 +20,7 @@ class MongoOperator<T : Any>(
|
||||
constructor(clazz: Class<T>, database: MongoDatabase) : this(database.getCollection(MongoUtil.collectionName(clazz), clazz), clazz)
|
||||
|
||||
private val fields = clazz.declaredFields.filter {
|
||||
it.isAccessible = true
|
||||
!it.isTransient() && it.getAnnotation(Ignore::class.java) == null
|
||||
}
|
||||
|
||||
@ -49,17 +50,17 @@ class MongoOperator<T : Any>(
|
||||
|
||||
@Suppress("SpellCheckingInspection")
|
||||
fun upsert(update: Bson, where: Bson, options: UpdateOptions = UpdateOptions()): UpdateResult {
|
||||
return update(convertToBson(update), where, options.upsert(true))
|
||||
return update(update, where, options.upsert(true))
|
||||
}
|
||||
|
||||
fun add(field: KProperty1<T, Number>, value: Number, where: Bson, options: UpdateOptions = UpdateOptions()): UpdateResult {
|
||||
fun add(field: KProperty1<T, Number?>, value: Number, where: Bson, options: UpdateOptions = UpdateOptions()): UpdateResult {
|
||||
return upsert(
|
||||
Update { field inc value },
|
||||
where, options
|
||||
)
|
||||
}
|
||||
|
||||
fun inc(field: KProperty1<T, Number>, where: Bson): UpdateResult {
|
||||
fun inc(field: KProperty1<T, Number?>, where: Bson): UpdateResult {
|
||||
return add(field, 1, where)
|
||||
}
|
||||
|
||||
|
@ -28,10 +28,11 @@ object MongoUtil {
|
||||
fun convertToBson(entity: Any): Bson {
|
||||
val bson = Document()
|
||||
entity.javaClass.declaredFields.filter {
|
||||
it.isAccessible = true
|
||||
!it.isTransient() && it.getAnnotation(Ignore::class.java) == null
|
||||
}.forEach {
|
||||
val value = it.get(entity) ?: return@forEach
|
||||
bson[MongoUtil.fieldName(it)] = value
|
||||
bson[fieldName(it)] = value
|
||||
}
|
||||
return bson
|
||||
}
|
||||
|
@ -7,6 +7,8 @@ import kotlin.reflect.KProperty
|
||||
object Update {
|
||||
operator fun invoke(action: Update.() -> Bson) = this.action()
|
||||
|
||||
infix fun Bson.and(update: Bson): Bson = Updates.combine(this, update)
|
||||
fun combine(vararg updates: Bson): Bson = Updates.combine(*updates)
|
||||
|
||||
infix fun KProperty<*>.set(value: Any): Bson = Updates.set(MongoUtil.fieldName(this), value)
|
||||
fun KProperty<*>.unset(): Bson = Updates.unset(MongoUtil.fieldName(this))
|
||||
|
Loading…
Reference in New Issue
Block a user