【发布时间】:2019-11-22 05:41:13
【问题描述】:
我想在 mongoDB 4.2 中创建集合,但我想检查它是否存在?我正在使用 Node.JS 和 Express,但我没有使用 Mongoose。
【问题讨论】:
我想在 mongoDB 4.2 中创建集合,但我想检查它是否存在?我正在使用 Node.JS 和 Express,但我没有使用 Mongoose。
【问题讨论】:
请试试这个 ::
const MongoClient = require('mongodb').MongoClient;
// Connection URL
const url = 'your DB url';
// Database Name
const dbName = 'your DB name';
// Create a new MongoClient
const client = new MongoClient(url);
// Use connect method to connect to the Server
client.connect(async function (err) {
if (err) console.log('Err::', err)
console.log("Connected successfully to server");
const collection = await client.db(dbName).listCollections({}, { nameOnly: true }).toArray()
console.log('List of all collections :: ', JSON.stringify(collection))
client.close();
});
【讨论】:
db.getCollectionNames() 应该可以在 shell/任何客户端(如 robo3T)中工作..
createCollection() 它应该会出错如果集合已经存在于同一个数据库中,则退出。
您可以使用listCollections 查找数据库中的所有集合,然后遍历returned array 以获取名称。
db.listCollections().toArray(function(err, items) {
console.log(items)
//and u can loop over items to fetch the names
});
【讨论】: