我正在使用 Next Js 和 MongoDB 创建其余 API,并进行类型脚本检查。当创建通过 Id 获取帖子的路由之一时,出现以下错误:
(property) NextApiRequest.query: Partial<{
[key: string]: string | string[];
}>
Object of query values from url
Argument of type 'string | string[] | undefined' is not assignable to parameter of type 'string | number | ObjectId | ObjectIdLike | Buffer | Uint8Array | undefined'.
Type 'string[]' is not assignable to type 'string | number | ObjectId | ObjectIdLike | Buffer | Uint8Array | undefined'.
Type 'string[]' is missing the following properties from type 'Uint8Array': BYTES_PER_ELEMENT, buffer, byteLength, byteOffset, and 3 more.ts(2345)
这是我的 API 代码:
import nc from "next-connect";
import { ObjectId } from "mongodb";
import clientPromise from "../../../../../lib/mongodb";
import type { NextApiRequest, NextApiResponse } from "next";
const onError = (
err: any,
_req: NextApiRequest,
res: NextApiResponse,
next: any
) => {
console.error(err);
res.status(500).end(err.toString());
// OR: you may want to continue
next();
};
const handler = nc({
onError,
})
.get(async (_req: NextApiRequest, res: NextApiResponse) => {
const client = await clientPromise;
const db = client.db(process.env.MONGO_DB);
try {
const _id = new ObjectId(_req.query.postId); // gets the type error here
const result = await db.collection("posts").findOne({ _id });
res.json(result);
} catch (error) {
console.log("show error", error);
res.send({
status: 400,
message: "Internal Server Error" || error,
});
}
})
我还尝试在从 _req.query 解构 postId 时传递默认值,如下所示:
const { postId = '' } = _req.query || { };
const result = await db.collection("posts").findOne({ _id: new ObjectId(postId) }); // gets the type error here as well
但是错误仍然存在。
消除错误的唯一方法是,如果我不使用 new ObjectId 类包装 ID,但不会从数据库中获取任何结果。这本身是有效的。文档id是一种对象id,因此需要添加。
我对使用相同框架创建 Next Js 和 API 还很陌生。任何有助于解决和理解此问题的帮助将不胜感激。
最佳答案
ObjectId
接受此类型
'string | number | ObjectId | ObjectIdLike | Buffer | Uint8Array | undefined'
但是查询值的类型是:string |字符串[] |未定义
string[]
并不常见。试试这个
const _id = new ObjectId(_req.query.postId as unknown as string);
如果你不想类型转换,你可以使用
let _id;
if (ObjectId.isValid(_req.query.postId)){
_id = new ObjectId(_req.query.postId);
}
// then if _id exists run the query
if(_id){
const result = await db.collection("posts").findOne({ _id });
res.json(result)
}
关于node.js - 在 MongoDB Node JS Rest API 中使用 ObjectId 类时出现类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75314492/