node.js - MongoDB updateOne 为 upsertedId 返回 null

标签 node.js mongodb

我正在尝试获取更新文档的 upsertedId,但返回的是 null

这是更新文档并尝试返回 result.upsertedId 的函数:

 async function run() {
          try {
            await client.connect()
            const collection = client.db("database").collection("collection")
            const filter = { username: `${username}`}
            const options = { upsert: true };
            const updateDoc = {
              $set: { date: new Date(), topartists: data.body.items, toptracks: toptracks }
            };
            await collection.updateOne(filter, updateDoc, options)
              .then(result => {
                console.log(`${result.matchedCount} document(s) matched the filter, updated ${result.modifiedCount} document(s)`)
                console.log(result.upsertedId)
              })
            console.log('done1')
          } finally {
            await client.close();
          }
        }

这是函数的控制台输出:

1 document(s) matched the filter, updated 1 document(s)
null
done1

我刚刚开始使用 MongoDB,这里的最终目标是获得 _id .它可以工作,但我的数据库中没有任何内容(当它必须创建一个新文档而不是更新一个文档时)。

最佳答案

事实并非如此。

您的日志清楚地表明 - 您的查询匹配了 1 个文档并且它更新了一个文档。

如果您的更新导致插入,那么您的更新操作的响应将具有更新插入 ID。 - 表示,匹配计数为 0。

关于node.js - MongoDB updateOne 为 upsertedId 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63567909/

相关文章:

node.js - 通过 nodemailer 发送的电子邮件进入 gmail 的垃圾邮件

c++ - 构建 mongo c++ 驱动程序

Node.js apache 基准测试

node.js - 当对象存在时,Mongoose findById 对于第一个对象返回 null

node.js - 如何在 node.js 中处理标准输出

node.js - 如何用 Mongoose 排除数组类型字段

mongodb - 无法在 ubuntu 中找到 mongod.conf 文件

arrays - 如何将字段(具有 K-V 对的对象数组)转换为仅具有值的数组数组?

php - Mongo获取id以某个数字结尾的用户

xcode - 使用 homebrew 和 Xcode 8.1.1 安装 Mongodb 失败