我正在使用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 module v2.0.x
答案 0 :(得分:-2)
重新阅读$set
文档https://docs.mongodb.org/v3.0/reference/operator/update/set/它明确表示会取代那里的内容。因此,如果文档存在与否,它并不关心它为什么不返回错误。如果查询存在且相同,则需要其他运算符来拒绝查询。
编辑/更新以下评论
您必须触发错误才能知道数据库是否已作为集合,以及它是否是最新的。因此,需要额外的操作员来检查找到的集合是否已经具有更新的信息。
MongoDB使用$
表示的运算符$gt or $lt or $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); });