简体   繁体   English

尝试将 mongoose 连接到我的 mongodb 并出现浏览器内错误

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

The code compiles fine in my editor, but only shows up in my browser app:代码在我的编辑器中编译得很好,但只出现在我的浏览器应用程序中:

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;

Unhandled Runtime Error TypeError: mongoose__WEBPACK_IMPORTED_MODULE_2___default(...).connect is not a function未处理的运行时错误 TypeError: mongoose__WEBPACK_IMPORTED_MODULE_2___default(...).connect is not a function

I was just trying to get it to connect to my mongodb and honestly I tried a few things that were suggested to me by chatgpt because I am learning to code using it so I just asked it to fix it but it couldn't.我只是想让它连接到我的 mongodb,老实说,我尝试了 chatgpt 向我建议的一些事情,因为我正在学习使用它进行编码,所以我只是要求它修复它,但它不能。 I'm not sure what else I should say.我不确定我还应该说些什么。

I got this error at first:一开始我遇到了这个错误:

TypeError: mongoose.connect is not a function类型错误:mongoose.connect 不是 function

so I tried:所以我试过:

This error is usually caused when you forget to import the mongoose module in your file.此错误通常是由于您忘记在文件中导入 mongoose 模块而导致的。 Please make sure you have the following line at the top of your file:请确保您的文件顶部有以下行:

javascript Copy code javascript 复制代码

const mongoose = require("mongoose");

Additionally, make sure that you have installed the mongoose package in your project by running npm install mongoose.此外,通过运行 npm install mongoose,确保您已在项目中安装了 mongoose package。

and this:和这个:

The error is occurring because you are trying to call the connect function on the mongoose module, but mongoose has not been imported correctly.发生错误是因为您试图在 mongoose 模块上调用连接 function,但 mongoose 尚未正确导入。

Try changing this line:尝试更改此行:

javascript Copy code javascript 复制代码

const mongoose = require('mongoose');

to this:对此:

python Copy code python 复制代码

import mongoose from 'mongoose';

This should resolve the error and allow you to connect to the MongoDB database using Mongoose.这应该可以解决错误并允许您使用 Mongoose 连接到 MongoDB 数据库。

then this:然后这个:

The issue is that the mongoose module is being imported using the require statement which is commonly used for CommonJS modules.问题是 mongoose 模块是使用 CommonJS 模块常用的 require 语句导入的。 However, since you are using a Next.js application which is built using ES6 modules, you need to use the import statement instead:但是,由于您使用的是使用 ES6 模块构建的 Next.js 应用程序,因此您需要改用 import 语句:

javascript Copy code 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');
});

So, following Matt's comment, I fed his response to chatGPT and this is the code it spit out, which fixes the issue:因此,根据 Matt 的评论,我将他的回复提供给 chatGPT,这是它吐出的代码,它解决了这个问题:

Here's how you can use getServerSideProps to fix the error in your code:以下是如何使用 getServerSideProps 修复代码中的错误:

javascript Copy code 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;

This way, the mongoose code will only run on the server-side and will not interfere with the client-side rendering.这样mongoose代码只会在服务端运行,不会干扰客户端渲染。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我正在尝试使用mongoose设置我的mongoDB数据库,但是出现错误“ mongoose默认的Promise库已弃用” - I am trying to setup my mongoDB database using mongoose, but i getting an error “mongoose default promise library is deprecated” 如何将 mongoose 中的鉴别器连接到我的父文档? 尝试导入数据时出错 - How do I connect my discriminators in mongoose to my parent document? Getting errors when trying to import data 尝试将对象导入猫鼬模式时出错 - getting error trying to import object into mongoose schema 尝试将 mongoose 与 vue 一起使用并出现错误 - Trying to use mongoose with vue and getting error 简单的浏览器时间轴 - Simple In-Browser Timeline Mongoose.connect 不抛出任何错误,当 Mongodb 未运行时 - Mongoose.connect not throwing any error, when Mongodb is not running 出现错误:querySrv ECONNREFUSED _mongodb._tcp.auctiondbcluster.s6rzg.mongodb.net。 当我离线时尝试连接到 localhost - Getting Error: querySrv ECONNREFUSED _mongodb._tcp.auctiondbcluster.s6rzg.mongodb.net. When trying to connect to localhost when I am offline 无法使用mongoose连接到mongoDB - Unable to connect to mongoDB using mongoose Feathers-mongoose $like 查询 MongoDb 出现错误 - Feathers-mongoose $like query for MongoDb getting Error 将 MongoDB (mongoose) uri 移动到 .env 文件时出错 - Getting error when moving MongoDB (mongoose) uri to .env file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM