0
嗨,爲什麼我得到重複輸入錯誤。如果文檔在數據庫中,我會事先檢查。我的模型需要idName
的唯一性。我從JSON數組中加載數據,prooven只是假的,沒有真正的條目。MongoDb重複輸入錯誤
async.map recipe.zutaten,
(ingredient, cb) ->
#Save all ingredients
ingredient.idName = ingredient.name.replace(/[^a-zA-Z0-9]+/gi, "").toLowerCase()
ingredientModel.find({ idName: ingredient.idName }, (err, ingredientFound) ->
return next err if err
ingredientsJson = {"idName":ingredient.idName, "name":ingredient.name, "amount":ingredient.amount}
#if found just pass it to recipes
if ingredientFound? && ingredientFound.length > 0
ingredientsJson.prooven = true
return cb null, ingredientsJson
#if not found evaluate if to save
else
#if not prooven just add the json to recipes
if(ingredient.prooven? && ingredient.prooven == false)
ingredientsJson.prooven = false
return cb null, ingredientsJson
#if prooven save it into database
else
ingredientDBObject = new ingredientModel()
ingredientDBObject.name = ingredient.name
ingredientDBObject.idName = ingredient.idName
ingredientDBObject.save((err) ->
return cb err if err
ingredientsJson.prooven = true
return cb null, ingredientsJson
)
)
...
錯誤
{ [MongoError: insertDocument :: caused by :: 11000 E11000 duplicate key error index: database.ingredients.$idName_1 dup key: { : "zitronensaft" }]
name: 'MongoError',
message: 'insertDocument :: caused by :: 11000 E11000 duplicate key error index: database.ingredients.$idName_1 dup key: { : "zitronensaft" }',
index: 0,
code: 11000,
errmsg: 'insertDocument :: caused by :: 11000 E11000 duplicate key error index: database.ingredients.$idName_1 dup key: { : "zitronensaft" }' }
我想這個問題是關係找到的異步特性。即使cb尚未返回,異步也會遍歷配料。我已經在find函數中移動了'ingredient.idName = ingredient.name.replace(/ [^ a-zA-Z0-9] +/gi,「」).toLowerCase()'。 – 2015-04-01 18:41:39