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找到MongoDB里的文档并修改数据。
另外想问下:怎么在提问时直接显示图片而不是只放URL?看别人的回答都能直接显示图片,我这里只能显示URL链接。
内容的提问来源于stack exchange,提问作者Jeong-Woo
相关产品推荐
相关产品推荐

