next.js 如何在给定string _id的客户端使用ObjectId?

dm7nw8vv  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(74)

如何在字符串中获取给定_id的文档?
客户端的代码如下所示:

'use client'

...

const Page(){

      ...

      fetch("api/get_data", {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                query: {
                    "$match": { "_id": str_id }
                },
                limit: 1
            })
        })
}

还有我的next.js13后端API,它实际上获取了数据/api/get_data/route.ts

export async function POST(request: Request) {

    ...

    await DATA_COLLECTION?.aggregate([
                body.query
            ])?.limit(body.limit)?.toArray()

}

我会像这样使用ObjectId

"$match": {
    "_id": new ObjectId(str_id)
}

但它给出了错误:

Module not found: Can't resolve 'child_process'

https://nextjs.org/docs/messages/module-not-found

Import trace for requested module:
./node_modules/mongodb/lib/client-side-encryption/auto_encrypter.js
./node_modules/mongodb/lib/index.js

7tofc5zh

7tofc5zh1#

找到解here

{ $match: { $expr : { $eq: [ '$_id' , { $toObjectId: str_id } ] } } }

在fetch中写为:

fetch("api/get_data", {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                query: { $match: { $expr : { $eq: [ '$_id' , { $toObjectId: str_id } ] } } }},
                limit: 1
            })
        })

相关问题