mongodb - 通过文档的 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();
});
});
解决方案
推荐阅读
- powershell - PowerShell 上的异步代码执行?
- java - Java/Swing - 为 TextField 设置标题
- python - 如何在 pyspark Hive SQL 中获取等效的 postgres 命令“nth_value”?
- impala - impala shell 命令将镶木地板文件导出为 csv
- python - Keras 神经网络中的模型精度非常低和计算错误
- python - wxpython - create a wx.html.HtmlWindow() that has highlighted text
- html - 将多行包装为一个单元
- javascript - 如何在 d3.js 中绘制 GeoJson 数据
- javascript - 将 Meteor Blaze 与 Autoform 一起使用,但表单不会显示
- node.js - NVM - 将 NodeJS 更新到最新版本 - Ubuntu 18.04