Node.js - Mongoose - Check if a collection exists

前端 未结 3 1199
时光取名叫无心
时光取名叫无心 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();
        });
    });
    

提交回复
热议问题