node.js - 在 MongoDB Node JS Rest API 中使用 ObjectId 类时出现类型错误

标签 node.js typescript mongodb next.js objectid

我正在使用 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/

相关文章:

javascript - mongodb 在保存数据时抛出错误(拓扑被破坏)

javascript - 在成功安装 sqlite3 后尝试运行代码时如何修复此 "module not found error"?

javascript - 如何切换变量格式不一致的大小写

linux - bash 不会在远程 ssh 命令上加载 Node

html - 如何滚动到 Angular 页面中的 anchor

mongodb - 一起使用 MongoDB 和 Neo4j

mysql - 从索引表中高效查询

node.js - 升级到最新的 Node 和 npm 后,npm i 无法工作

reactjs - 如何将 TypeScript 与 withRouter、connect、React.Component 和自定义属性一起使用?

mongodb - 如何获得聚合 - $addFields 上的 $group 计数结果?