0

使用给定的代码,我尝试连接到 mongo db,按事件类型选择事件,而不是断言我刚刚选择的内容

@Grab('org.mongodb:mongodb-driver:3.4.1')

import com.mongodb.MongoClient
import com.mongodb.MongoClientURI
import com.mongodb.DBCollection
import com.mongodb.DB
import com.mongodb.DBCursor;
import com.mongodb.BasicDBObject
import com.mongodb.DBObject;
import groovy.json.JsonSlurper;

class MongoService {
    private MongoClient mongoClient

    def login = "user"
    def password = "pass"
    def host = "host"
    def port = port
    def databaseName = 'mongodb'

    public MongoClient client() {
        mongoClient = new MongoClient(new MongoClientURI(
               new StringBuilder("mongodb://").
               append(login).append(":").
               append(password).append("@").
               append(host).append(":").
               append(port).append("/").
               append(databaseName).toString()))
                              ;

        return mongoClient
    }

    public DBCollection collection(collectionName) {
        DB db = client().getDB(databaseName)

        return db.getCollection(collectionName)
    }
}

def service = new MongoService(databaseName: 'mongodb') 
def foo = service.collection('events')

BasicDBObject whereQuery = new BasicDBObject();
    whereQuery.put("EventType", "test");

    DBCursor cursor = foo.find(whereQuery);
    while (cursor.hasNext()) {
        log.info(cursor.next())

    }
    def json = cursor.next()

    def slurper = new groovy.json.JsonSlurper()
     def result = slurper.parseText(json)
      assert result.EventType == "test"

我在第 52 行返回 soapui 返回 java.util.NoSuchElementException 错误,在 mongodb 中使用相同的查询手动检查db.getCollection('events').find({"EventType": "test"}) 返回 1 个对象。我不知道如何使它工作......:/

4

1 回答 1

0

问题是您访问光标的方式。

当您调用时,您已经用尽了光标log.info(cursor.next()),当您这样做时cursor.next(),没有可访问的元素,这就是该异常的原因。

DBCursor cursor = foo.find(whereQuery);
while (cursor.hasNext()) {
    log.info(cursor.next())
}
def json = cursor.next()

因此,解决方法是更改​​代码以cursor.next()在 while 循环中的每次迭代中调用一个。

于 2017-01-10T17:34:33.647 回答