簡體   English   中英

嘗試將 mongoose 連接到我的 mongodb 並出現瀏覽器內錯誤

[英]Trying to connect mongoose to my mongodb and getting in-browser error

代碼在我的編輯器中編譯得很好,但只出現在我的瀏覽器應用程序中:

import React, { useState } from 'react';
import mongoose from 'mongoose';

mongoose.connect(process.env.DATABASE_URL, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
  console.log('Connected to the database');
});

const Index = () => {
    const [postText, setPostText] = useState('');

    const handleSubmit = (e) => {
        e.preventDefault();
        // add code here to handle form submission and create a post
        setPostText('');
    }

    return (
        <div>
            <h1>Welcome to My Social Media App</h1>
            <form onSubmit={handleSubmit}>
                <textarea value={postText} onChange={(e) => setPostText(e.target.value)} placeholder="What's on your mind?"/>
                <button type="submit">Post</button>
            </form>
        </div>
    )
}

export default Index;

未處理的運行時錯誤 TypeError: mongoose__WEBPACK_IMPORTED_MODULE_2___default(...).connect is not a function

我只是想讓它連接到我的 mongodb,老實說,我嘗試了 chatgpt 向我建議的一些事情,因為我正在學習使用它進行編碼,所以我只是要求它修復它,但它不能。 我不確定我還應該說些什么。

一開始我遇到了這個錯誤:

類型錯誤:mongoose.connect 不是 function

所以我試過:

此錯誤通常是由於您忘記在文件中導入 mongoose 模塊而導致的。 請確保您的文件頂部有以下行:

javascript 復制代碼

const mongoose = require("mongoose");

此外,通過運行 npm install mongoose,確保您已在項目中安裝了 mongoose package。

和這個:

發生錯誤是因為您試圖在 mongoose 模塊上調用連接 function,但 mongoose 尚未正確導入。

嘗試更改此行:

javascript 復制代碼

const mongoose = require('mongoose');

對此:

python 復制代碼

import mongoose from 'mongoose';

這應該可以解決錯誤並允許您使用 Mongoose 連接到 MongoDB 數據庫。

然后這個:

問題是 mongoose 模塊是使用 CommonJS 模塊常用的 require 語句導入的。 但是,由於您使用的是使用 ES6 模塊構建的 Next.js 應用程序,因此您需要改用 import 語句:

javascript 復制代碼

import mongoose from 'mongoose';

mongoose.connect(process.env.DATABASE_URL, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
  console.log('Connected to the database');
});

因此,根據 Matt 的評論,我將他的回復提供給 chatGPT,這是它吐出的代碼,它解決了這個問題:

以下是如何使用 getServerSideProps 修復代碼中的錯誤:

javascript 復制代碼

import React, { useState } from 'react';
import mongoose from 'mongoose';

const Index = () => {
    const [postText, setPostText] = useState('');

    const handleSubmit = (e) => {
        e.preventDefault();
        // add code here to handle form submission and create a post
        setPostText('');
    }

    return (
        <div>
            <h1>Welcome to My Social Media App</h1>
            <form onSubmit={handleSubmit}>
                <textarea value={postText} onChange={(e) => setPostText(e.target.value)} placeholder="What's on your mind?"/>
                <button type="submit">Post</button>
            </form>
        </div>
    )
}

export async function getServerSideProps(context) {
    await mongoose.connect(process.env.DATABASE_URL, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
    });

    const db = mongoose.connection;
    db.on('error', console.error.bind(console, 'connection error:'));
    db.once('open', () => {
        console.log('Connected to the database');
    });

    return {
        props: {},
    };
}

export default Index;

這樣mongoose代碼只會在服務端運行,不會干擾客戶端渲染。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM