我现在通过mongoose将数据发送到mongodb,在获取它的api路由时,会抛出此错误

const addChoice = async (e) => {
        try {
            e.preventDefault();
            const res = await fetch("/api/sendChoice", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify({
                    choiceSeq: choice,
                    checkSubmit: true,
                }),
            });
            console.log(res);
            router.push("/home");
        } catch (error) {
            console.log(error);
        }
    };

错误发生在const res = await fetch("/api/sendChoice" ,{

在终端服务器中显示错误

在inspect元素中,错误如下

我找不到任何与修复此问题相关的内容,我甚至不明白try 自己解决此问题意味着什么.

我的项目中的一些其他相关代码

import { getSession } from "next-auth/client";
import dbConnect from "../../helpers/dbConnect";
import Choice from "../../models/Choice";

export default async function sendChoice(req, res) {
    try {
        const session = await getSession({ req });
        await dbConnect();
        if (!session) {
            res.status(401).send("You are not signed in");
            return;
        }
        if (req.method === "POST") {
            console.log(req.body);
            const { choiceSeq, checkSubmit } = req.body;
            console.log(choiceSeq, checkSubmit);
            const userId = session.user.id;
            const nameP = session.user.name;
            const choice = new Choice({
                user: userId,
                name: nameP,
                choiceSeq,
                checkSubmit,
            });
            await choice.save();
            res.status(200).send("Choice saved");
        } else {
            res.status(400).send("Bad request");
        }
    }
    catch (error) {
        console.log(error);
    }
}

mongodb模式

import mongoose, { Schema } from 'mongoose';

const ChoiceSchema = new Schema({
    user: {
        type: Schema.Types.ObjectId,
        ref: 'User',
    },
    name: {
        type: String,
    },
    choiceSeq: {
        type: Array,
        default: [],
    },
    checkSubmit: {
        type: Boolean,
    }
});

mongoose.models = {};

export default mongoose.model('Choice', ChoiceSchema);

推荐答案

导致此错误的是17.5.0版的最新更新.必须将node js重新安装到版本16.14.0 LTS.您应该始终使用LTS版本

Mongodb相关问答推荐

Mongo聚合的具体格式

MongoDB乘以对象值?

NodeJS + MongoDB:使用 findOne () 从集合中获取数据

增加嵌套对象中的值?

如何在 MongoDb 中进行类似于嵌套 Sql Select 查询的嵌套查询

在 Heroku 上使用 Node 读取、写入和存储 JSON

用 Redis 查询?

字段类型在 MongoDB 索引中是否重要?

MongoDB展开多个数组

MongoDB:多个 $elemMatch

无法从 MongoDb C# 中的 BsonType ObjectId 反序列化字符串

如何防止MongoDB在查找文档时返回对象ID?

填充mongoose后查找

Mongoose Select 要从 findOneAndUpdate 返回的字段

在 Ubuntu 13.10 (saucy) 中安装 Mongodb PHP 扩展的最简单方法?

MongoDB备份计划

如何使用 mgo 从 golang 中的 mongodb 集合中 Select 所有记录

Mongoid 不在查询中

如何在 Windows 上停止 mongodb 服务器?

Meteor `Deps.autorun`与`Collection.observe`