我正在尝试获取更新文档的 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/