2016-06-13 67 views
3

代码检查数据库中是否存在文档(使用预保存钩子),如果不存在,则插入它。它工作正常,但不适用于第一个文档。它总是插入。看起来这第一个文档不会触发预存储钩子。猫鼬总是插入第一个文档并跳过预保存钩子

Model = require('./model') 
var model = new Model(); 

//Before saving, check if the product exists 
Model.schema.pre('save', function (next) { 
    var self = this; 
    Model.findOne({apiProductId: self.apiProductId}, function (err, product) { 
     if (!product) { 
      next(); 
     } 
     else { 
      next(new Error("Product exists: " + self.apiProductId)); 
     } 
    }); 
}); 

model.save(function (err, document) { 
    if (err) { 
     console.log(err); 
    } 
     else { 
      console.log('Inserted: ' + document.apiProductId); 
     } 
}); 
+0

mongo的** _ upsert _ **功能可以帮助吗?也许这[stackoverflow线程](http://stackoverflow.com/questions/9661081/mongoose-update-upsert)可以澄清一些事情。 – FlorianE

回答

1

预保存钩子不是避免重复的正确方法。你应该使用findOneAndUpdate

你的问题可能是:

  1. 您正在尝试以异步方式保存多个文件:挂钩执行顺序是不可预测的
  2. 您已经创建了apiProductId稀疏索引,你正在检查的null值。