T
T
TRUEC0DER2022-04-05 14:59:36
Java
TRUEC0DER, 2022-04-05 14:59:36

How to call MongoDB methods outside the main class?

There is a connect method in the main class that connects to the MongoDB database, you need to call methods from other classes, but I can’t understand how exactly this can be done

package com.test.testplugin;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bukkit.plugin.java.JavaPlugin;

public final class TestPlugin extends JavaPlugin {
    public static TestPlugin plugin;

    private MongoClient mongoClient;
    private MongoDatabase mongoDatabase;
    private MongoCollection<Document> mongoCollection;

    @Override
    public void onEnable() {
        connect();
        // Plugin startup logic
    }

    @Override
    public void onDisable() {
        // Plugin shutdown logic
    }

    public void connect() {
        MongoClient client = new MongoClient(new MongoClientURI("ссылка"));
        MongoDatabase database = client.getDatabase("база");
        MongoCollection<Document> collection = database.getCollection("коллекция");
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Roo, 2022-04-05
@xez

class SomeClass {
    private final JavaPlugin plugin;
    
    public SomeClass(JavaPlugin plugin) {  // тут надо передать в конструктор экземпляр TestPlugin
       this.plugin = plugin;
    }

    public void someMethod() {
        plugin.connect();
        // TODO:: implement your awesome business logic
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question