axios TypeError:mongodb.ObjectId不是构造函数

lvjbypge  于 2024-01-07  发布在  iOS
关注(0)|答案(3)|浏览(165)

[Code:app.post('/update-item',function(req,res){ db.collection(' items ').findOneAndUpdate({_id:new mongodb.ObjectId(req.body.id)},{$set:{text:req.body.text}},function(req,res){ res.send(“Success”)
[1]

k5ifujac

k5ifujac1#

你的代码看起来有点不对劲,我会这样处理它:

  1. const MyModel = require('<PATH_FOR_YOUR_MODEL>');
  2. app.post("/update-item", async (req,res)){
  3. const id = req.body.id
  4. const text = req.body.text
  5. await MyModel findByIdAndUpdate(id, text);
  6. res.status(200).send('Success');
  7. }

字符串

sauutmhj

sauutmhj2#

我在学习布拉德schiff的Learn JavaScript: Full-Stack from Scratch课程时也遇到了同样的问题。问题似乎是文件顶部的这行代码:

  1. let mongodb = require('mongodb');

字符串
这似乎还不够,我通过添加下面的行来修复它:

  1. let mongoObjectId = require('mongodb').ObjectId;


并使用了mongoObjectId而不是mongodb.ObjectId(在代码中将这两个相互更改)
我还将第一行改为:

  1. let mongodb = require('mongodb').MongoClient;


因为它之前也造成了一些其他的错误,

展开查看全部
a8jjtwal

a8jjtwal3#

首先声明顶部的ObjectId!!

  1. const ObjectId = require('mongodb').ObjectId

字符串
然后,使用变量ObjectId而不是mongodb.ObjectId!!
例如,

  1. db.collection('items').findOneAndUpdate({ _id: new ObjectId(req.body.id) }, { $set: { text: req.body.text } }, function () {
  2. res.send("Success")
  3. })

相关问题