mongodb 客户端 nodejs 检查数据库是否存在否则运行“async.each”来创建集合

问题描述 投票:0回答:0

你好,我遇到了一个问题,mongodb 客户端试图检查集合是否存在
这是连接功能:

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);
    }

这是一个检查集合是否存在的函数,如果没有则创建


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();
             }
};

我也试试

db.listCollections({name: "collection1"}).toArray()
查收藏

node.js mongodb async.js
© www.soinside.com 2019 - 2024. All rights reserved.