这是代码:获取错误'ReferenceError:初始化之前无法访问'parsePayload''请帮忙const express = require(\'express\'); const { createToDo,updateToDo } =
这是代码:出现错误, 'ReferenceError: Cannot access 'parsePayload' before initialization'
请帮忙
const express = require("express");
const { createToDo, updateToDo } = require("./types");
const { todo } = require("./db");
const app = express();
app.use(express.json());
app.post('/to-do',async function(req,res){
const createPayload = req.body;
const parsePayload = createToDo.safeParse(parsePayload);
if(!parsePayload.success){
res.status(411).json({
"msg" : "you sent the wrong input"
})
return;
}
await todo.create({
title : createPayload.title,
description : createPayload.description,
completed : false
})
res.json({
"msg" : "To Do Created"
})
})
app.get('/to-do',async function(req,res){
const todos = await todo.find();
console.log(todos);
res.json({
todos
})
})
app.put('/to-do',async function(req,res){
const updatePayload = req.body;
const parsePayload = updateToDo.safeParse(parsePayload);
if(!parsePayload.success){
res.status(411).json({
"msg" : "you send the wrong id or input"
})
return;
}
await todo.update({
_id : req.body.id
},{
completed : true
})
res.json({
"msg" : "todo marked updated"
})
})
app.listen(3000);
parsepaylod 在第 13 行声明,我试图在同一行使用它。仍然出现错误
从键入导入 Any从 bson 导入 ObjectId从 pydantic_core 导入 core_schema 类 PyObjectId(ObjectId):\'\'\'要创建一个验证 bson ObjectID 的 pydantic 对象&qu...
from typing import Any
from bson import ObjectId
from pydantic_core import core_schema
class PyObjectId(ObjectId):
"""To create a pydantic Object that validates bson ObjectID"""
@classmethod
def __get_pydantic_core_schema__(cls, _source_type: Any, _handler: Any) -> core_schema.CoreSchema:
return core_schema.json_or_python_schema(
json_schema=core_schema.str_schema(),
python_schema=core_schema.union_schema(
[
core_schema.is_instance_schema(ObjectId),
core_schema.chain_schema(
[
core_schema.str_schema(),
core_schema.no_info_plain_validator_function(cls.validate),
]
),
]
),
serialization=core_schema.plain_serializer_function_ser_schema(lambda x: str(x)), # noqa W0108
)
@classmethod
def validate(cls, value) -> ObjectId:
if not ObjectId.is_valid(value):
raise ValueError("Invalid ObjectId")
return ObjectId(value)
class GoalRecordStored(BaseModel):
"""Goal Record Model."""
player_id: PyObjectId = Field(..., validation_alias="Player ID")
date: datetime = Field(validation_alias="Date")
我试图将 推送 player_id
为 , ObjectId
但无法这样做,并且它被保存 MongoDB
为 string
而不是 ObjectId
。我该如何改变这种情况?
我尝试对类进行了很多更改,但都没有帮助。我一直尝试 player_id
以不同的方式推动,但它总是存储一个字符串,而不是我想要的方式。