假设我有一个带有 2 个集合的 MongoDB 实例 - places 和 people。
一个典型的 places 文档如下所示:
{
"_id": "someID"
"name": "Broadway Center"
"url": "bc.example.net"
}
people 文档看起来像:
{
"name": "Erin"
"place": DBRef("places", "someID")
"url": "bc.example.net/Erin"
}
有什么方法可以验证 people 集合中每个 文档的 places DBRef?
最佳答案
没有官方/内置方法来测试DBRefs的有效性,所以必须手动进行验证。
我写了一个小脚本——validateDBRefs.js:
var returnIdFunc = function(doc) { return doc._id; };
var allPlaceIds = db.places.find({}, {_id: 1} ).map(returnIdFunc);
var peopleWithInvalidRefs = db.people.find({"place.$id": {$nin: allPlaceIds}}).map(returnIdFunc);
print("Found the following documents with invalid DBRefs");
var length = peopleWithInvalidRefs.length;
for (var i = 0; i < length; i++) {
print(peopleWithInvalidRefs[i]);
}
运行时:
mongo DB_NAME validateDBRefs.js
将输出:
Found the following documents with invalid DBRefs
513c4c25589446268f62f487
513c4c26589446268f62f48a
关于validation - 如何验证 MongoDB 集合中的 DBRefs?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15341666/