我遇到使用MongoJack和updateById方法的问题。
在来自MongoJack的javadoc中,它声明方法updateById(K,T)(link to javadoc)可以与K一起使用,T作为要保存的对象。但是,以下代码和测试表明情况并非如此。完整的源代码可以在Github找到:https://github.com/nilsmagnus/mongojackupdatebyid/。
要保存的对象:
package no.nils.mongoupdate;
public class Scenario {
public String _id;
public String name;
public Scenario(String name) {
this.name = name;
}
public String get_id() {
return _id;
}
public String getName() {
return name;
}
}
更新课程:
package no.nils.mongoupdate;
import org.mongojack.JacksonDBCollection;
import org.mongojack.WriteResult;
import com.mongodb.DB;
import com.mongodb.DBCollection;
class ScenarioStorage {
private JacksonDBCollection<Scenario, String> scenarioCollection;
public ScenarioStorage(DB db) {
DBCollection dbCollection = db.getCollection("scenario");
scenarioCollection = JacksonDBCollection.wrap(dbCollection, Scenario.class, String.class);
}
public void update(Scenario scenario) {
WriteResult<Scenario, String> writeResult = scenarioCollection.updateById(scenario._id, scenario);
if (writeResult.getError() != null) throw new RuntimeException(writeResult.getError());
}
public String saveNewScenario(Scenario scenario) {
WriteResult<Scenario, String> writeResult = scenarioCollection.insert(scenario);
if (writeResult.getError() != null) throw new RuntimeException(writeResult.getError());
return writeResult.getSavedId();
}
public Scenario getScenario(String id) {
return scenarioCollection.findOneById(id);
}
}
显示失败的测试:
package no.nils.mongoupdate;
import java.net.UnknownHostException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Before;
import org.junit.Test;
import com.mongodb.DB;
import com.mongodb.MongoClient;
public class ScenarioStorageTest {
private ScenarioStorage storage;
@Before
public void createDb() throws UnknownHostException {
MongoClient mongoClient = new MongoClient("localhost", 27017);
DB db = mongoClient.getDB("junittest");
storage = new ScenarioStorage(db);
}
@Test
public void shouldUpdateNameAfterUpdate() {
Scenario scenario = new Scenario("first");
final String id = storage.saveNewScenario(scenario);
scenario._id = id;
scenario.name = "newname";
storage.update(scenario);
Scenario updated = storage.getScenario(id);
assertNotNull("Stored object should have been fetched.", updated.name);
assertEquals("The stored object should now have the name 'newname'.", updated.name, "newname");
}
}
第一次断言测试失败。请告知我是否误解了mongojack的javadoc或我可能犯的任何其他错误。
答案 0 :(得分:1)
好的,javadoc和教程已经破解。解决方案是将注释@ObjectId添加到_id字段。
@ObjectId
public String _id;