MongoDb重复输入错误

时间:2015-04-01 17:29:16

标签: mongodb mongoose

您好我为什么会遇到重复的输入错误。如果文档在数据库中,我会提前检查。我的模型需要idName的唯一性。我从JSON数组加载数据,prooven只是false,没有条目为true。

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" }' }

1 个答案:

答案 0 :(得分:0)

问题与async.map有关,它不等待回调。使用async.mapSeries解决了这个问题。 Map Series等待cb被解析: https://github.com/caolan/async#mapSeries

...
async.mapSeries recipes,
  (recipe, next) ->  
    ...      
    async.mapSeries recipe.zutaten,
      (ingredient, cb) ->
           ...