0

Hello I got a problem that mongodb client try to check if collection exist or not
Here is the connect function:

const { MongoClient } = require("mongodb");
const async = require("async");
const uri = process.env.MONGODB_URL || "mongodb://127.0.0.1:27017";

const client = new MongoClient(uri);

const onConnect = async function (callback) {
    console.log('Connecting to MongoDB...');
    try {
        await client.connect();
        let db = client.db('mydb');
        console.log('Connected to MongoDB successfully');
        callback(null, db);
    } catch (err) {
        callback(err);
    }

Here is a function that check for collection exist and create if none


exports.initialize = function(callback) {
    // For collections in the future
    const collections = [
        "collection1",
        "collection1",
        "collection1"
    ];

    // This check collection not working
    onConnect(function(_err, db) {
        try {
          // db.listCollections().toArray(function(_err, collectionsList) {
          //     if (collectionsList.find(collection => collection.name === "collection1")) {
          //         db.close();
          //         return callback();
          //     }
          // }
          // Else, create collections
          async.each(collections, function(collection, callback) {
          db.createCollection(collection, function(_err, result) {
          // Console did log out but collection still create a stuck
          console.log("Collection " + collection + " was created with success");
          if (collection === "collection1") {
            // Data not insert
            db.collection("collection1").insertOne(data, function(_err, result) {
            console.log("Default data added !");
            return callback();
          }) else {
               return callback();
             }
};

I also try db.listCollections({name: "collection1"}).toArray() to check collection

4
  • What is your question? "I got a problem" or "not working" is not so helpful. Commented Apr 12, 2023 at 4:32
  • In MongoDB you don't have to create collections, they are created automatically when you insert any data. And you should print the error messages, it will help a lot. Commented Apr 12, 2023 at 4:34
  • Hi @WernfriedDomscheit my problem is it work but it also not work since I run it and the collection it running but the terminal get freeze and I can't do anything Commented Apr 12, 2023 at 8:15
  • Pleaase provide enough debugging details. For example, exact errors you see... Also, you are using a try without catch; it might be useful while debugging Commented Apr 13, 2023 at 6:35

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.