【发布时间】:2016-02-28 12:22:25
【问题描述】:
问题
在向应用程序报告写操作成功之前是否更新了 mongodb 索引,还是在后台运行索引更新?如果它们在后台运行:有没有办法等待索引更新完成?
背景
我有一个文件
person1obj = {
email: 'user@domain.tld',
[...]
}
在people 集合中,其中一个唯一 索引应用于email 字段。现在我想插入另一个文档
person2obj = {
email: 'user@domain.tld',
[...]
}
显然,在插入person2 之前,我必须更改person1 的email 字段。使用猫鼬,代码看起来像
mongoose.model('Person').create(person1obj, function (err, person1) {
// person1 has been saved to the db and 'user@domain.tld' is
// added to the *unique* email field index
// change email for person1 and save
person1.email = 'otheruser@domain.tld';
person1.save(function(err, person1) {
// person1 has been updated in the db
// QUESTION: is it guaranteed that 'user@domain.tld' has been removed from
// the index?
// inserting person2 could fail if the index has not yet been updated
mongoose.model('Person').create(person2obj, function (err, person2) {
// ...
});
});
});
我看到我的单元测试随机失败,错误为E11000 duplicate key error index,这让我怀疑索引更新是否在后台运行。
这个问题可能与 mongodb 的 write concern 有关,但我找不到任何关于索引更新实际过程的文档。
【问题讨论】:
-
索引更新是写操作的一部分。它们不在后台运行。现在,如果您正在从辅助节点读取数据,那么您可能会得到陈旧的数据,但这与索引的工作方式无关。
-
@SergioTulentsev 谢谢!你有指向解释行为的文档的指针吗?