无法从 MongoDB 数据库获取数据?

发布于 2025-01-13 06:07:16 字数 6497 浏览 0 评论 0原文

我正在尝试连接到 MongoDB 数据库,但它没有检索任何数据。我在 MongoDB 上将其设置为 Twitter-Clone 项目,其中包含带有 tweets 表和 users 表的 twitter-clone 集合。

当我从命令行启动应用程序时,我分别从 tweetsDAO.js 和 index.js 收到这两条消息:

tweetsDAO.js has established collection handles.
Listening on port 5000

当我转到 http://localhost:5000/api/v1/tweets 时,我从以下位置收到此消息tweets-controller.js,这似乎表明它运行了搜索并返回空:

{"tweets":[],"page":0,"filters":{},"entries_per_page":20,"total_results":0}

这些是正在使用的文件:

.env 文件:

TWITTCLONE_DB_URI=mongodb+srv://admin:<thisismypassword>@twitter-clone.3wvps.mongodb.net/twitter_clone?retryWrites=true&w=majority
TWITTCLONE_NS=twitter_clone
PORT=5000

index.js:

import app from "./server.js";
import mongodb from "mongodb";  // Used to access mongodb.
import dotenv from "dotenv";    // Used to access environment variables.
import TweetsDAO from "./dao/tweetsDAO.js";
dotenv.config();    // Load in environment variables.
const MongoClient = mongodb.MongoClient;    // Access our Mongo client.

const port = process.env.PORT || 8000;  // Use port from .env file, or 8000.

MongoClient.connect(    // Connect to database.
    process.env.TWITTCLONE_DB_URI, // The environment variable with username & password for MongoDB.
    {
        wtimeout: 2500,      // After 2500 miliseconds the request times out.
    })
    .catch(err => {      // If error, log to console and exit the process.
        console.error(err.stack);  
        process.exit(1);
    })
    .then(async client => {     // Succesful connection to database.
        await TweetsDAO.injectDB(client);
        app.listen(port, () => {    // Starts our web server.
            console.log(`Listening on port ${port}`);
        })
    }
);

server.js:

import express from "express";
import cors from "cors";
import allRoute from "./api/all.route.js";

const app = express();

app.use(cors());    // Apply our middleware, CORS module.
app.use(express.json());    // Our server can accept JSON in the body of a request. Previously required body-parser, but express can do this now.

app.use("/api/v1/tweets", allRoute);    // Accessed with http://localhost:5000/api/v1/tweets
app.use("*", (req, res) => res.status(404).json({ error: "not found" }));    // A route that doesn't exist in our route file.

export default app; // Export this file as a module.

all.route.js:

import express from "express";
import TweetsCtrl from "./tweets.controller.js";

const router = express.Router();    // The different routes ppl can go to.

// router.route("/").get((req, res) => res.send("Hello world!"));  // Our demo route. Going to root responds with HW.
router.route("/").get(TweetsCtrl.apiGetTweets);   // Going to root returns this method.

export default router;

tweets-controller.js:

import TweetsDAO from "../dao/tweetsDAO.js";

export default class TweetsController {
    static async apiGetTweets (req, res, next) {   // User may or may not be passing variables in with the URL.
        const tweetsPerPage = req.query.resturantsPerPage ? parseInt(req.query.tweetsPerPage, 10) : 20  // Checks if tweetsPerPage is being passed in and then converts to an int. Otherwise default is 20 tweets per page.
        const page = req.query.page ? parseInt(req.query.page, 10) : 0  // Checks if page is being passed in and then converts to an int. Otherwise default is page 0.

        let filters = {};   // Filters is set to default.

        const { tweetsList, totalNumTweets } = await TweetsDAO.getTweets({  // Pass in filters, page, & tweetsPerPage. Returns the tweetsList & totalNumTweets.
            filters,
            page,
            tweetsPerPage,
        });

        let response = {    // Return the json response with all this data.
            tweets: tweetsList,
            page: page,
            filters: filters,
            entries_per_page: tweetsPerPage,
            total_results: totalNumTweets,
        }
        res.json(response);
    }

tweetsDAO.js:

import mongodb from "mongodb";
const ObjectId = mongodb.ObjectId;  // Use ObjectID to convert a String to a MongoDB object.

let tweets;

export default class TweetsDAO {
    static async injectDB(conn) {
        if (tweets) {  // If the tweet already exists.
            return;
        }
        try {
            tweets = await conn.db(process.env.TWITTCLONE_NS).collection("tweets");  // If it doesn't exist already, it will be created when trying to add a document to it.
            console.error("tweetsDAO.js has established collection handles.")
        } catch (e) {
            console.error(`Unable to establish collection handles in tweetsDAO: ${e}`)
        }
    }

    static async getTweets({   // Gets a list of all tweets in the database.
        filters = null,     // Default by null, unless user passes something in.
        page = 0,   // Defaults to page 0.
        tweetsPerPage = 20,    // Defaults to 20 tweets per page.
    } = {}) {
        let query;   // If query isn't set to anything, it returns all tweets.
        if (filters) {  // User can search by name, cuisine, or zipcode.
            if ("name" in filters) {
                query = { $text: { $search: filters["name"] } } // Specified in MongoDB will check a certain field.         
        }

        let cursor;

        try {
            cursor = await tweets
            .find(query)    // Find all tweets in the database that match this query.

        } catch (e) {   // If there is no query, returns an error.
            console.error(`Unable to issue find command, ${e}`);
            return { tweetsList: [], totalNumTweets: 0 }
        }

        const displayCursor = cursor.limit(tweetsPerPage).skip(tweetsPerPage * page); // To locate which page user is on, use the limit and current page to determine what to display.

        try {
            const tweetsList = await displayCursor.toArray();
            const totalNumTweets = await tweets.countDocuments(query);

            return { tweetsList, totalNumTweets }
        } catch (e) {
            console.error(
                `Unable to convert cursor to array or problem counting documents, ${e}`
            );
            return { tweetsList: [], totalNumTweets: 0 }
        }
    }
}

在我正在查看的另一个项目中,提交空查询命令似乎会返回表中的所有数据。所以我认为我做错了什么但无法弄清楚?

I'm trying to connect to a MongoDB database and it's not retrieving any data. I have it set up on MongoDB as Twitter-Clone project, which contains twitter-clone collection with tweets table and users table.

When I launch the app from command line, I'm getting these 2 messages from tweetsDAO.js and index.js respectively:

tweetsDAO.js has established collection handles.
Listening on port 5000

When I go to http://localhost:5000/api/v1/tweets I'm getting this message from tweets-controller.js, which seems to indicate it ran a search and came back empty:

{"tweets":[],"page":0,"filters":{},"entries_per_page":20,"total_results":0}

These are the files being used:

.env file:

TWITTCLONE_DB_URI=mongodb+srv://admin:<thisismypassword>@twitter-clone.3wvps.mongodb.net/twitter_clone?retryWrites=true&w=majority
TWITTCLONE_NS=twitter_clone
PORT=5000

index.js:

import app from "./server.js";
import mongodb from "mongodb";  // Used to access mongodb.
import dotenv from "dotenv";    // Used to access environment variables.
import TweetsDAO from "./dao/tweetsDAO.js";
dotenv.config();    // Load in environment variables.
const MongoClient = mongodb.MongoClient;    // Access our Mongo client.

const port = process.env.PORT || 8000;  // Use port from .env file, or 8000.

MongoClient.connect(    // Connect to database.
    process.env.TWITTCLONE_DB_URI, // The environment variable with username & password for MongoDB.
    {
        wtimeout: 2500,      // After 2500 miliseconds the request times out.
    })
    .catch(err => {      // If error, log to console and exit the process.
        console.error(err.stack);  
        process.exit(1);
    })
    .then(async client => {     // Succesful connection to database.
        await TweetsDAO.injectDB(client);
        app.listen(port, () => {    // Starts our web server.
            console.log(`Listening on port ${port}`);
        })
    }
);

server.js:

import express from "express";
import cors from "cors";
import allRoute from "./api/all.route.js";

const app = express();

app.use(cors());    // Apply our middleware, CORS module.
app.use(express.json());    // Our server can accept JSON in the body of a request. Previously required body-parser, but express can do this now.

app.use("/api/v1/tweets", allRoute);    // Accessed with http://localhost:5000/api/v1/tweets
app.use("*", (req, res) => res.status(404).json({ error: "not found" }));    // A route that doesn't exist in our route file.

export default app; // Export this file as a module.

all.route.js:

import express from "express";
import TweetsCtrl from "./tweets.controller.js";

const router = express.Router();    // The different routes ppl can go to.

// router.route("/").get((req, res) => res.send("Hello world!"));  // Our demo route. Going to root responds with HW.
router.route("/").get(TweetsCtrl.apiGetTweets);   // Going to root returns this method.

export default router;

tweets-controller.js:

import TweetsDAO from "../dao/tweetsDAO.js";

export default class TweetsController {
    static async apiGetTweets (req, res, next) {   // User may or may not be passing variables in with the URL.
        const tweetsPerPage = req.query.resturantsPerPage ? parseInt(req.query.tweetsPerPage, 10) : 20  // Checks if tweetsPerPage is being passed in and then converts to an int. Otherwise default is 20 tweets per page.
        const page = req.query.page ? parseInt(req.query.page, 10) : 0  // Checks if page is being passed in and then converts to an int. Otherwise default is page 0.

        let filters = {};   // Filters is set to default.

        const { tweetsList, totalNumTweets } = await TweetsDAO.getTweets({  // Pass in filters, page, & tweetsPerPage. Returns the tweetsList & totalNumTweets.
            filters,
            page,
            tweetsPerPage,
        });

        let response = {    // Return the json response with all this data.
            tweets: tweetsList,
            page: page,
            filters: filters,
            entries_per_page: tweetsPerPage,
            total_results: totalNumTweets,
        }
        res.json(response);
    }

tweetsDAO.js:

import mongodb from "mongodb";
const ObjectId = mongodb.ObjectId;  // Use ObjectID to convert a String to a MongoDB object.

let tweets;

export default class TweetsDAO {
    static async injectDB(conn) {
        if (tweets) {  // If the tweet already exists.
            return;
        }
        try {
            tweets = await conn.db(process.env.TWITTCLONE_NS).collection("tweets");  // If it doesn't exist already, it will be created when trying to add a document to it.
            console.error("tweetsDAO.js has established collection handles.")
        } catch (e) {
            console.error(`Unable to establish collection handles in tweetsDAO: ${e}`)
        }
    }

    static async getTweets({   // Gets a list of all tweets in the database.
        filters = null,     // Default by null, unless user passes something in.
        page = 0,   // Defaults to page 0.
        tweetsPerPage = 20,    // Defaults to 20 tweets per page.
    } = {}) {
        let query;   // If query isn't set to anything, it returns all tweets.
        if (filters) {  // User can search by name, cuisine, or zipcode.
            if ("name" in filters) {
                query = { $text: { $search: filters["name"] } } // Specified in MongoDB will check a certain field.         
        }

        let cursor;

        try {
            cursor = await tweets
            .find(query)    // Find all tweets in the database that match this query.

        } catch (e) {   // If there is no query, returns an error.
            console.error(`Unable to issue find command, ${e}`);
            return { tweetsList: [], totalNumTweets: 0 }
        }

        const displayCursor = cursor.limit(tweetsPerPage).skip(tweetsPerPage * page); // To locate which page user is on, use the limit and current page to determine what to display.

        try {
            const tweetsList = await displayCursor.toArray();
            const totalNumTweets = await tweets.countDocuments(query);

            return { tweetsList, totalNumTweets }
        } catch (e) {
            console.error(
                `Unable to convert cursor to array or problem counting documents, ${e}`
            );
            return { tweetsList: [], totalNumTweets: 0 }
        }
    }
}

In another project I am looking at, it seems that submitting an empty query command returns all the data from the table. So I think I have done something wrong but can't figure it out?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文