and*_*chy 5 database mongoose mongodb
mongodb 索引是在写入操作成功报告给应用程序之前更新还是索引更新在后台运行?如果它们在后台运行:有没有办法等待索引更新完成?
我有一个文件
person1obj = {
email: 'user@domain.tld',
[...]
}
Run Code Online (Sandbox Code Playgroud)
在对字段应用唯一people索引的集合中。现在我想插入另一个文档email
person2obj = {
email: 'user@domain.tld',
[...]
}
Run Code Online (Sandbox Code Playgroud)
显然,我必须改变之前email的字段才能插入。对于猫鼬,代码看起来像person1person2
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) {
// ...
});
});
});
Run Code Online (Sandbox Code Playgroud)
我看到我的单元测试随机失败并出现错误E11000 duplicate key error index,这让我想知道索引更新是否在后台运行。
这个问题可能与 mongodb 的写入问题有关,但我找不到任何有关索引更新实际过程的文档。