You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB中ObjectId使用报错及文档更新匹配失败求助

求助:MongoDB通过_id更新数据失败问题

排查了三个小时还是找不到解决办法,试过两种方案都有问题:

  • 安装了bson-objectid库
  • 使用mongoose的Types属性:
    import mongoose from "mongoose";
    const { ObjectId } = mongoose.Types;
    

但两种方法都触发相同的错误:"method expression is not of function type"

原代码(使用ObjectId版本)

import {MongoClient, ObjectId} from "mongodb";
async function handler(req, res){
    if(req.method === "POST"){
        const data = req.body;
        const client = await MongoClient.connect("mongoDB URL")
        const db = client.db();
        const postItCollection = db.collection("postIts");
        const result = await postItCollection.updateOne({_id: ObjectId(data.id)}, {$set:{positionX:data.y, positionY:data.x}});
        console.log(result);
        client.close();
        res.status(201).json({message:"success"})
    }
}
export default handler;

这段代码运行后直接报错:"method expression is not of function type"

不使用ObjectId的代码

import {MongoClient, ObjectId} from "mongodb";
async function handler(req, res){
    if(req.method === "POST"){
        const data = req.body;
        const client = await MongoClient.connect("mongoDB URL")
        const db = client.db();
        const postItCollection = db.collection("postIts");
        const result = await postItCollection.updateOne({_id: data.id}, {$set:{positionX:data.y, positionY:data.x}});                                
        console.log(result);
        client.close();
        res.status(201).json({message:"success"})
    }
}
export default handler;

这段代码能收到成功响应,但实际没匹配到对应的_id,查询结果如下:
无法匹配_id的查询结果

我现在只需要实现:通过_id找到MongoDB里的文档并修改数据。

另外想问下:怎么在提问时直接显示图片而不是只放URL?看别人的回答都能直接显示图片,我这里只能显示URL链接。

内容的提问来源于stack exchange,提问作者Jeong-Woo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 14:41:43