如何修复错误(TypeError:无法分配给对象“#<QueryCursor>”的只读属性“map”)

Pra*_*yan 10 typeerror fetch mongoose mongodb next.js

我通过 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);
    }
};
Run Code Online (Sandbox Code Playgroud)

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

在终端服务器中出现错误

错误 - TypeError:无法分配给对象“#<QueryCursor>”的只读属性“map”

在检查元素中,错误如下
这

我找不到与解决此问题相关的任何内容,我什至不明白该错误意味着什么,试图自己解决它。

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

api/sendChoice

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

小智 29

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


Pra*_*yan 9

这个问题最近发生了,显然是在最新版本的节点上发生的。

问题链接

所以你可以将节点版本更改为旧版本,它就会被修复。我使用的是节点版本 v14.19.0


Lor*_*ord 7

如果你正在使用 Docker,那么提供一个版本即可解决问题。

前:

FROM node:alpine

Run Code Online (Sandbox Code Playgroud)

现在

FROM node:16.5.0-alpine

WORKDIR /app
COPY package.json .
RUN npm install --only=prod
COPY . .

CMD ["npm", "start"]
Run Code Online (Sandbox Code Playgroud)