gpt4 book ai didi

node.js - 如何在 mongodb nodejs 驱动程序中获取更新确认?

转载 作者:可可西里 更新时间:2023-11-01 09:17:43 24 4
gpt4 key购买 nike

我正在使用 mongodb npm 模块通过 nodejs 连接到我的 mongo 数据库。

我的简单用例是我需要更新集合中的文档,该文档可能存在也可能不存在。

因此,如果文档存在,我应该能够更新它并在我的 API 响应中发送确认。

如果文档不存在,我应该用文档不存在的适当消息进行响应。

基本上是一个非常简单的用例。

这是我更新的方式:

var MongoClient = require('mongodb').MongoClient;

MongoClient.connect(url, function(conn_err, db) {
if (conn_err) {
console.log("Error connecting to mongodb server!!");
console.error(conn_err);
} else {
console.log("Connected to mongodb server!!");
var collection = db.collection("test");

collection.updateOne(query, {"$set": data}, {w: "majority"}, function (err, result) {
console.error(err);
console.log(result);
});
}
});

现在在 result 的回调中,我得到一个包含很多东西的对象,但主要是:

result: { ok: 1, nModified: 1, n: 1 }
...
matchedCount: 1,
modifiedCount: 1,
upsertedId: null,
upsertedCount: 0

这就是我的麻烦开始的地方。

1) 如果文档存在并且更新了,我得到:

result: { ok: 1, nModified: 1, n: 1 },
...
matchedCount: 1,
modifiedCount: 1,
upsertedId: null,
upsertedCount: 0

2) 如果文档存在但未更新(因为 $set 中的字段值已经与数据库中的字段值相同)我得到:

result: { ok: 1, nModified: 0, n: 1 },
...
matchedCount: 1,
modifiedCount: 0,
upsertedId: null,
upsertedCount: 0

3) 但如果文档不存在,我会得到:

result: { ok: 1, nModified: 0, n: 1 },
...
matchedCount: 1,
modifiedCount: 0,
upsertedId: null,
upsertedCount: 0

基本上我如何区分情况 2) 和 3)?我不想为每个更新执行多个查询。

谁能请教一下?

注意:mongodb v3.0.7,nodejs v4.2.2,mongodb npm模块v2.0.x

最佳答案

重新阅读$set 文档https://docs.mongodb.org/v3.0/reference/operator/update/set/它明确表示它将取代那里的东西。所以它不关心文档是否存在,这就是它不返回错误的原因。如果查询存在并且相同,则需要其他运算符来拒绝该查询。

编辑/更新以下评论

您必须触发错误才能知道数据库是否已经作为集合以及它是否是最新的。因此需要额外的运算符(operator)来检查找到的集合是否已经具有更新的信息。MongoDB 使用用 $ 表示的运算符,所以 $gt 或 $lt 或 $nor (大于,小于,选择除此之外的所有内容)还有更多,但我会让你探索的可能性。 https://docs.mongodb.org/v3.0/reference/operator/query/nor/

此行 需要根据您的表达式和运算符触发错误。当你开始工作时不要只是抛出错误允许程序继续下一个因为这个错误并不意味着打破(抛出)那个错误它只是告诉你嘿数据库有这个并且它已经更新了,出错时会让您知道什么也没做。

collection.updateOne(query, {"$set": data},{w: "majority"},function (err,result){ console.error(err);console.log(result); });

关于node.js - 如何在 mongodb nodejs 驱动程序中获取更新确认?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33820590/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com