简体   繁体   中英

How to get all the collections of MongoDB?

I want to get access to all the collections of my MongoDB database. But I am unable to do so.

I am using mongoose.connection.db.getCollection(collection_name) just above the listen part of code but console is saying mongoose.connection.db.getCollection is not a function.

Here is my code

 import express from "express"; import mongoose from "mongoose"; import Messages from "./messages.js"; import dynamicModel from "./messagesRoom.js"; import cors from "cors"; // app configuration const app = express(); const port = process.env.PORT || 9000; //middleware app.use(express.json()); app.use(cors()); // DB Configuration const url = "mongodb+srv://username:password@cluster0.zp9dc.mongodb.net/Whatsapp_MERN"; mongoose.connect(url, {useCreateIndex: true, useNewUrlParser: true, useUnifiedTopology: true}).then(()=> console.log('mongoDB is connected')).then(err => console.log(err)); const db = mongoose.connection; db.once('open', () => { console.log("DB is connected"); const msgCollection = db.collection('messagecontents'); const changeStream = msgCollection.watch(); changeStream.on('change', (change) => { console.log(change); if(change.operationType === 'insert'){ const msgDetails = change.fullDocument; pusher.trigger('messages', 'inserted', { name: msgDetails.name, message: msgDetails.message, timestamp: msgDetails.timestamp, received: msgDetails.received, }) } else{ console.log('Error triggering pusher'); } }) }) // API routes app.get("/", (req, res) => { res.status(200).send("Hello World"); }) app.get("/messages/sync", async (req, res) => { await Messages.find( (err, data) => { if(err){ console.log(err); res.status(500).send(err); }else{ res.status(200).send(data); } }) }) app.post("/changeChat", (req, res) => { const collection_name = req.body.chatName; let collection = mongoose.connection.db.getCollection("collection_name"); console.log(collection); }) // listening part app.listen(port, () => console.log(`listening on port number ${port}`));

please suggest me a way using which I can get access to collections of database according to the name I am using.

You can see this discussion: Trying to get a list of collections from mongoose . I tested this code and it worked.

mongoose.connection.on('open', function (ref) {
    console.log('Connected to mongo server.');
    //trying to get collection names
    mongoose.connection.db.listCollections().toArray(function (err, names) {
        console.log(names); // [{ name: 'dbname.myCollection' }]
        module.exports.Collection = names;
    });
})
mongoose.connection.on('open', function (ref) {
    mongoose.connection.db.listCollections().toArray(function(err, names){
        console.log(names)
    })
})

Try this code block below "mongoose.connect()", the 'listCollections()' function will return the list of all the collection in the respective database and 'toArray()' function will convert that list into array, then we simply log the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM