【问题标题】:How to get all the collections of MongoDB?如何获取 MongoDB 的所有集合?
【发布时间】:2021-07-05 22:10:18
【问题描述】:

我想访问我的 MongoDB 数据库的所有集合。 但我做不到。

我在代码的监听部分上方使用 mongoose.connection.db.getCollection(collection_name) 但控制台说 mongoose.connection.db.getCollection 不是函数。

这是我的代码

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

请给我建议一种方法,让我可以根据我使用的名称访问数据库集合。

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    mongoose.connection.on('open', function (ref) {
        mongoose.connection.db.listCollections().toArray(function(err, names){
            console.log(names)
            })
        }

    试试“mongoose.connect()”下面的代码块,“listCollections()”函数将返回相应数据库中所有集合的列表,“toArray()”函数将该列表转换为数组,然后我们只需记录数组。

    【讨论】:

    • 虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-19
    • 1970-01-01
    相关资源
    最近更新 更多