Node.js - Mongoose - Check if a collection exists

前端 未结 3 1181
时光取名叫无心
时光取名叫无心 2020-12-01 18:20

I need to insert some data using mongoose but the name of the collection is provided by the user at the moment of the insertion, so I first have to check if the collection e

相关标签:
3条回答
  • 2020-12-01 18:26

    This works for me (mongoose version 5.1.1):

    const mongoose = require('mongoose');
    const mongoURI = 'mongodb://localhost:27017/mydb'
    // notice the mongoose.createConnection instead of mongoose.connect
    const conn = mongoose.createConnection(mongoURI);
    conn.on('open', function () {
        conn.db.listCollections().toArray(function (err, collectionNames) {
          if (err) {
            console.log(err);
            return;
          }
            console.log(collectionNames);
            conn.close();
        });
    });
    
    0 讨论(0)
  • 2020-12-01 18:28

    Find collection in collection's list

    public function CollectionExists($collectionName)
        {
            $mongo = new Mongo();
            $collectionArr = $mongo->selectDB('yourrec')->listCollections();
            if (in_array($collectionName, $collectionArr)) {
                return true;
            }
            return false;
        }
    
    0 讨论(0)
  • 2020-12-01 18:47

    Option 2 is probably the cleanest. Assuming you have a Mongoose Connection object named conn that's been opened using mongoose.createConnection, you can access the native mongo Db object via conn.db. From there you can call collectionNames which should provide what you're looking for:

    conn.db.collectionNames(function (err, names) {
        // names contains an array of objects that contain the collection names
    });
    

    You can also pass a collection name as a parameter to collectionNames to filter the results to just what you're looking for.

    Mongoose 4.x Update

    In the 2.x version of the MongoDB native driver that Mongoose 4.x uses, collectionNames has been replaced by listCollections which accepts a filter and returns a cursor so you would do this as:

    mongoose.connection.db.listCollections({name: 'mycollectionname'})
        .next(function(err, collinfo) {
            if (collinfo) {
                // The collection exists
            }
        });
    
    0 讨论(0)
提交回复
热议问题