如何将Android应用程序连接到MongoDB针脚?

时间:2019-03-11 21:45:23

标签: android database mongodb nosql

我一直在关注本教程:

https://code.tutsplus.com/tutorials/how-to-use-mongodb-stitch-in-android-apps--cms-31877

但是我陷入了第5步(建立连接)和第6步(插入文档)的困境。我真的是Android Studio和创建android应用程序的新手,并且提供的代码确实没有向我显示所有需要放置的位置的上下文。

我了解所发生的一切,但是本教程对于将代码放置在何处才能建立与数据库的连接似乎有些含糊。

谢谢您的协助!

1 个答案:

答案 0 :(得分:0)

这可能会有所帮助。来自mongodb网站(登录时)...示例片段:

final StitchAppClient client =
        Stitch.initializeDefaultAppClient("STITCH_CLIENT_APP_ID"); // replace STITCH_CLIENT_APP_ID with App ID

final RemoteMongoClient mongoClient =
        client.getServiceClient(RemoteMongoClient.factory, "mongodb1"); // replace mongodb1 with mongodb-atlas

final RemoteMongoCollection<Document> coll =
        mongoClient.getDatabase("<DATABASE>").getCollection("<COLLECTION>"); // replace <DATABASE> with Stitch db and <COLLECTION> with Stitch collection

client.getAuth().loginWithCredential(new AnonymousCredential()).continueWithTask(
        new Continuation<StitchUser, Task<RemoteUpdateResult>>() {

          @Override
          public Task<RemoteUpdateResult> then(@NonNull Task<StitchUser> task) throws Exception {
            if (!task.isSuccessful()) {
              Log.e("STITCH", "Login failed!");
              throw task.getException();
            }

            final Document updateDoc = new Document(
                    "owner_id",
                    task.getResult().getId()
            );

            updateDoc.put("number", 42);
            return coll.updateOne(
                    null, updateDoc, new RemoteUpdateOptions().upsert(true)
            );
          }
        }
).continueWithTask(new Continuation<RemoteUpdateResult, Task<List<Document>>>() {
  @Override
  public Task<List<Document>> then(@NonNull Task<RemoteUpdateResult> task) throws Exception {
    if (!task.isSuccessful()) {
      Log.e("STITCH", "Update failed!");
      throw task.getException();
    }
    List<Document> docs = new ArrayList<>();
    return coll
            .find(new Document("owner_id", client.getAuth().getUser().getId()))
            .limit(100)
            .into(docs);
  }
}).addOnCompleteListener(new OnCompleteListener<List<Document>>() {
  @Override
  public void onComplete(@NonNull Task<List<Document>> task) {
    if (task.isSuccessful()) {
      Log.d("STITCH", "Found docs: " + task.getResult().toString());
      return;
    }
    Log.e("STITCH", "Error: " + task.getException().toString());
    task.getException().printStackTrace();
  }
});