【问题标题】:Why updateOne doesn't update my collection?为什么 updateOne 不更新我的收藏?
【发布时间】:2019-12-20 10:39:12
【问题描述】:

我尝试从表单更新我的 MongoDB Atlas 集合中的文档。

我使用 Node.js、MongoDB 驱动程序和 bodyParser。

app.post("/quotes", (req, res) => {

    client.connect(err => {
        const db = client.db("test");
        const userID = {$eq: {"userID" : (req.body.userID)}}
        const update = {$set: {"name": (req.body.name)}}
        db.collection("customers").updateOne(userID, update, function(err, res) {
            console.log("POST /quotes");
            client.close();
        });
    });
    res.redirect("/user");

});

他们期望输出是我收藏中的更新文档,但实际输出在我的控制台日志中。

我的控制台日志:

the options [servers] is not supported
the options [caseTranslate] is not supported
the options [dbName] is not supported
the options [srvHost] is not supported
the options [credentials] is not supported

【问题讨论】:

  • 你自己设置了用户ID还是可能是mongo内置的ObjectId?如果是,那么您将不得不将 req.body.userID 更改为 new ObjectId(req.body.userID)
  • 用户ID是我自己设置的。它可以称为“用户名”。
  • 当我删除 app.post 并将 req.body.something 更改为一个值时,一切都在我的控制台中运行。但是,目标是使用 body-parser 获取表单并放入 MongoDB。
  • 你能告诉我们console.log(req.body)的输出是什么吗?

标签: javascript node.js mongodb express


【解决方案1】:

req.body 中的 userId 类型是 String,然后你必须将其转换为 ObjectId

 const mongo = require('mongodb');

 app.post("/quotes", (req, res) => {
 client.connect(err => {
    const db = client.db("test");


    try {
       mongoId = new mongo.ObjectId(req.body.userID);
    } catch (err) {
       if (err) return res.send({ error: err });
    }

    const userID = {$eq: {"userID" : (mongoId)}}
    const update = {$set: {"name": (req.body.name)}}
    db.collection("customers").updateOne(userID, update, function(err, res) {
        console.log("POST /quotes");
        client.close();
    });
   });
   res.redirect("/user");

});

【讨论】:

    【解决方案2】:

    我找到了!

    app.post("/quotes", (req, res) => {
    
        client.connect(err => {
            const db = client.db("test");
            const userID = {$eq: {"userID" : (req.body.userID)}}
            const update = {$set: {"name": (req.body.name)}}
            db.collection("customers").updateOne(userID, update, function(err, res) {
                console.log("POST /quotes");
            });
        });
        client.close();
        res.redirect("/user");
    
    });
    

    client.close();必须在函数之外。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-29
      • 1970-01-01
      • 1970-01-01
      • 2017-09-15
      • 2017-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多