mongodb client nodejs check if database exist else run "async.each" to create collection

30 views Asked by At

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

0

There are 0 answers