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)
如果你正在使用 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)
| 归档时间: |
|
| 查看次数: |
8166 次 |
| 最近记录: |