首页 > 解决方案 > 通过文档的 ID 使用 mongodb 更新文档

问题描述

如何通过文档的 ID 使用 mongodb 更新文档,这是我尝试做的:我正在从数据库中检索具有给定 ID 的文档,然后使用用户提供的信息构造一个新用户并更新用户信息到数据库。

 var MongoClient = require("mongodb").MongoClient;
    var url = "mongodb://localhost:27017/";

    MongoClient.connect(url, async function (err, db) {
      console.log(args);
      if (err) throw err;
      var dbo = db.db("UserApp");
      //retrieve the document with the given id from the db
      let user = await dbo
        .collection("users")
        .findOne({ _id: ObjectId(args.id) }, function (err, result) {
          if (err) throw err;
          console.log(result);
        });

      const myquery = { name: user.name };

      // construct a new user with the information provided by the user
      const newuser = new User({
        name: args.name,
        title: args.title,
        email: args.email,
      });
      // update the userinformation to the db
      dbo.collection("users").updateOne(myquery, newuser, function (err, res) {
        if (err) throw err;
        console.log("1 document updated");
        db.close();
      });
    });

标签: mongodb

解决方案


推荐阅读