我一直在使用this mongoose plugin执行代码库中经常使用的 findOrCreate。
我最近意识到,在创建唯一索引时执行多个异步findOrCreate 操作很容易导致E11000 重复键错误。
下面使用 Promise.all 可以描述一个示例。假设 name 是唯一的:
const promises = await Promise.all([
Pokemon.findOrCreate({ name: 'Pikachu' }),
Pokemon.findOrCreate({ name: 'Pikachu' }),
Pokemon.findOrCreate({ name: 'Pikachu' })
]);
上述肯定会失败,因为 findOrCreate 不是原子的。考虑到失败的原因是有道理的,但我想要的是一种解决此问题的简化方法。
我的很多模型都使用了findOrCreate,它们都存在这个问题。我想到的一个解决方案是创建一个插件来捕获错误,然后返回 find 的结果,但是,这里可能有更好的方法 - 可能是我不是的原生 Mongoose 意识到。
最佳答案
这当然取决于您对此的预期用途,但我会说总的来说“插件”不是必需的。您正在寻找的基本功能已经“内置”到 MongoDB 中 "upserts" .
根据定义,只要使用集合的“唯一键”发出“选择”文档的查询条件,“upsert”就不会产生“重复键错误”。在这种情况下 "name"。
简而言之,您可以通过简单地执行以下操作来模仿与上述相同的行为:
let results = await Promise.all([
Pokemon.findOneAndUpdate({ "name": "Pikachu" },{},{ "upsert": true, "new": true }),
Pokemon.findOneAndUpdate({ "name": "Pikachu" },{},{ "upsert": true, "new": true }),
Pokemon.findOneAndUpdate({ "name": "Pikachu" },{},{ "upsert": true, "new": true })
]);
这将在第一次调用时简单地“创建”该项目,而该项目尚不存在,或者“返回”现有项目。这就是“更新插入”的工作方式。
[
{
"_id": "5a022f48edca148094f30e8c",
"name": "Pikachu",
"__v": 0
},
{
"_id": "5a022f48edca148094f30e8c",
"name": "Pikachu",
"__v": 0
},
{
"_id": "5a022f48edca148094f30e8c",
"name": "Pikachu",
"__v": 0
}
]
如果您真的不关心“返回”每个调用而只想“更新或创建”,那么使用 bulkWrite() 发送一个 请求实际上效率要高得多。 :
// Issue a "batch" in Bulk
let result = await Pokemon.bulkWrite(
Array(3).fill(1).map( (e,i) => ({
"updateOne": {
"filter": { "name": "Pikachu" },
"update": {
"$set": { "skill": i }
},
"upsert": true
}
}))
);
因此,您不必等待服务器解析三个异步调用,而只需调用一个,它可以“创建”项目或“更新”您在$set 中使用的任何内容。发现时的修饰符。这些应用于每场比赛,包括第一场比赛,如果您想要“仅在创建时”,则有 $setOnInsert这样做。
当然这只是一个“写”,所以它真的取决于返回修改后的文档对你是否重要。因此,“批量”操作只是“写入”,它们不会返回,而是返回有关“批处理”的信息,指示“更新”的内容和“修改”的内容,如:
{
"ok": 1,
"writeErrors": [],
"writeConcernErrors": [],
"insertedIds": [],
"nInserted": 0,
"nUpserted": 1, // <-- created 1 time
"nMatched": 2, // <-- matched and modified the two other times
"nModified": 2,
"nRemoved": 0,
"upserted": [
{
"index": 0,
"_id": "5a02328eedca148094f30f33" // <-- this is the _id created in upsert
}
],
"lastOp": {
"ts": "6485801998833680390",
"t": 23
}
}
所以如果你确实想要“返回”,那么一个更典型的情况是在“创建”时分离你想要的数据和“更新”时需要的数据。注意到 $setOnInsert对于选择文档的“查询”条件中的任何值,本质上都是“隐含的”:
// Issue 3 pokemon as separate calls
let sequence = await Promise.all(
Array(3).fill(1).map( (e,i) =>
Pokemon.findOneAndUpdate(
{ name: "Pikachu" },
{ "$set": { "skill": i } },
{ "upsert": true, "new": true }
)
)
);
这将显示在每个原子事务的“序列”中应用的修改:
[
{
"_id": "5a02328fedca148094f30f38",
"name": "Pikachu",
"__v": 0,
"skill": 0
},
{
"_id": "5a02328fedca148094f30f39",
"name": "Pikachu",
"__v": 0,
"skill": 1
},
{
"_id": "5a02328fedca148094f30f38",
"name": "Pikachu",
"__v": 0,
"skill": 2
}
]
所以一般来说,您在这里想要的是“upserts”,并且根据您的意图,您可以使用单独的调用来返回每个修改/创建,或者您批量发出“写入”。
作为展示上述所有内容的完整 list :
const mongoose = require('mongoose'),
Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
mongoose.set('debug', true);
const uri = 'mongodb://localhost/test',
options = { useMongoClient: true };
const pokemonSchema = new Schema({
name: String,
skill: Number
},{ autoIndex: false });
pokemonSchema.index({ name: 1 },{ unique: true, background: false });
const Pokemon = mongoose.model('Pokemon', pokemonSchema);
function log(data) {
console.log(JSON.stringify(data, undefined, 2))
}
(async function() {
try {
const conn = await mongoose.connect(uri,options);
// Await index creation, otherwise we error
await Pokemon.ensureIndexes();
// Clean data for test
await Pokemon.remove();
// Issue 3 pokemon as separate calls
let pokemon = await Promise.all(
Array(3).fill(1).map( e =>
Pokemon.findOneAndUpdate({ name: "Pikachu" },{},{ "upsert": true, "new": true })
)
);
log(pokemon);
// Clean data again
await Pokemon.remove();
// Issue a "batch" in Bulk
let result = await Pokemon.bulkWrite(
Array(3).fill(1).map( (e,i) => ({
"updateOne": {
"filter": { "name": "Pikachu" },
"update": {
"$set": { "skill": i }
},
"upsert": true
}
}))
);
log(result);
let allPokemon = await Pokemon.find();
log(allPokemon);
// Clean data again
await Pokemon.remove();
// Issue 3 pokemon as separate calls
let sequence = await Promise.all(
Array(3).fill(1).map( (e,i) =>
Pokemon.findOneAndUpdate(
{ name: "Pikachu" },
{ "$set": { "skill": i } },
{ "upsert": true, "new": true }
)
)
);
log(sequence);
} catch(e) {
console.error(e);
} finally {
mongoose.disconnect();
}
})()
哪个会产生输出(对于那些懒得自己运行的人):
Mongoose: pokemons.ensureIndex({ name: 1 }, { unique: true, background: false })
Mongoose: pokemons.remove({}, {})
Mongoose: pokemons.findAndModify({ name: 'Pikachu' }, [], { '$setOnInsert': { __v: 0 } }, { upsert: true, new: true, remove: false, fields: {} })
Mongoose: pokemons.findAndModify({ name: 'Pikachu' }, [], { '$setOnInsert': { __v: 0 } }, { upsert: true, new: true, remove: false, fields: {} })
Mongoose: pokemons.findAndModify({ name: 'Pikachu' }, [], { '$setOnInsert': { __v: 0 } }, { upsert: true, new: true, remove: false, fields: {} })
[
{
"_id": "5a023461edca148094f30f82",
"name": "Pikachu",
"__v": 0
},
{
"_id": "5a023461edca148094f30f82",
"name": "Pikachu",
"__v": 0
},
{
"_id": "5a023461edca148094f30f82",
"name": "Pikachu",
"__v": 0
}
]
Mongoose: pokemons.remove({}, {})
Mongoose: pokemons.bulkWrite([ { updateOne: { filter: { name: 'Pikachu' }, update: { '$set': { skill: 0 } }, upsert: true } }, { updateOne: { filter: { name: 'Pikachu' }, update: { '$set': { skill: 1 } }, upsert: true } }, { updateOne: { filter: { name: 'Pikachu' }, update: { '$set': { skill: 2 } }, upsert: true } } ], {})
{
"ok": 1,
"writeErrors": [],
"writeConcernErrors": [],
"insertedIds": [],
"nInserted": 0,
"nUpserted": 1,
"nMatched": 2,
"nModified": 2,
"nRemoved": 0,
"upserted": [
{
"index": 0,
"_id": "5a023461edca148094f30f87"
}
],
"lastOp": {
"ts": "6485804004583407623",
"t": 23
}
}
Mongoose: pokemons.find({}, { fields: {} })
[
{
"_id": "5a023461edca148094f30f87",
"name": "Pikachu",
"skill": 2
}
]
Mongoose: pokemons.remove({}, {})
Mongoose: pokemons.findAndModify({ name: 'Pikachu' }, [], { '$setOnInsert': { __v: 0 }, '$set': { skill: 0 } }, { upsert: true, new: true, remove: false, fields: {} })
Mongoose: pokemons.findAndModify({ name: 'Pikachu' }, [], { '$setOnInsert': { __v: 0 }, '$set': { skill: 1 } }, { upsert: true, new: true, remove: false, fields: {} })
Mongoose: pokemons.findAndModify({ name: 'Pikachu' }, [], { '$setOnInsert': { __v: 0 }, '$set': { skill: 2 } }, { upsert: true, new: true, remove: false, fields: {} })
[
{
"_id": "5a023461edca148094f30f8b",
"name": "Pikachu",
"__v": 0,
"skill": 0
},
{
"_id": "5a023461edca148094f30f8b",
"name": "Pikachu",
"__v": 0,
"skill": 1
},
{
"_id": "5a023461edca148094f30f8b",
"name": "Pikachu",
"__v": 0,
"skill": 2
}
]
N.B The
$setOnInsertis also "implied" in all "mongoose" operations for the purpose of applying the__vkey. So unless you turn this off, that statement is always "merged" with whatever is issued and thus allows the{}in the first example "update" block which would be an error in the core driver due to no update modifier being applied, yet mongoose adds this one for you.Also note that
bulkWrite()does not actually reference the "schema" for the model and bypasses it. This is why there is no__vin those issued updates, and it does indeed bypass all validation as well. This is usually not an issue, but it is something you should be aware of.
关于javascript - 使用 Promise.all 避免唯一错误 E11000,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47164400/
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
很好奇,就使用rubyonrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提
假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于
我正在尝试使用ruby和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru
我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t
我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h