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);
}
});
mongo的** _ upsert _ **功能可以幫助嗎?也許這[stackoverflow線程](http://stackoverflow.com/questions/9661081/mongoose-update-upsert)可以澄清一些事情。 – FlorianE