我有一個名爲「products」的Sails.js模型,它是一個MongoDB集合。在模型中,我有一個beforeCreate()
掛鉤,它生成一個唯一的productId,如'YYMMDD-count`格式的'170921-00001',其中count是當天創建的記錄編號。這是我的模型看起來像:Sails.js中的數據庫調用beforeCreate()模型掛鉤導致驗證錯誤
module.exports = {
attributes: {
name: { type: 'string', required: true },
productId: { type: 'string', unique: true }
},
beforeCreate: function(values, next) {
var moment = require('moment');
// Generate the productId
Products.count({
createdAt: {
'>=': moment().format('YYYY-MM-DD'),
'<': moment(moment().format('YYYY-MM-DD')).add(1, 'days').format('YYYY-MM-DD')
}
}).exec(function(error, productCount) {
if (error) {
throw error;
}
var count = '',
totalPlaces = 5 - productCount.toString().length;
while (totalPlaces > 0) {
count = count + '0';
totalPlaces--;
}
values.productId = moment().format('YYMMDD') + '-' + (count + productCount);
next();
});
}
};
的問題是,該休息的時候我想多產品插入到集合在一個單一的數據庫調用。我得到以下錯誤:
debug: Error (E_VALIDATION) :: 1 attribute is invalid
MongoError: E11000 duplicate key error index: my-app.products.$productId_1 dup key: { : "170921-00002" }
at Function.MongoError.create (/Users/Nag/Code/my-app/web-service/node_modules/sails-mongo/node_modules/mongodb-core/lib/error.js:31:11)
at toError (/Users/Nag/Code/my-app/web-service/node_modules/sails-mongo/node_modules/mongodb/lib/utils.js:114:22)
at /Users/Nag/Code/my-app/web-service/node_modules/sails-mongo/node_modules/mongodb/lib/collection.js:658:23
at handleCallback (/Users/Nag/Code/my-app/web-service/node_modules/sails-mongo/node_modules/mongodb/lib/utils.js:95:56)
at resultHandler (/Users/Nag/Code/my-app/web-service/node_modules/sails-mongo/node_modules/mongodb/lib/bulk/ordered.js:421:14)
at /Users/Nag/Code/my-app/web-service/node_modules/sails-mongo/node_modules/mongodb-core/lib/connection/pool.js:455:18
at /Users/Nag/Code/my-app/web-service/node_modules/async-listener/glue.js:188:31
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickDomainCallback (internal/process/next_tick.js:128:9)
at process.fallback (/Users/Nag/Code/my-app/web-service/node_modules/async-listener/index.js:529:15)
Invalid attributes sent to undefined:
• productId
• A record with that `productId` already exists (`170921-00002`).
當我插入一條記錄,它工作正常,但是當我插入多條記錄,第一個記錄被插入,但以後每記錄生成該錯誤。是否因爲在鉤子計算出productId
之前插入文檔之前插入文檔?我該如何解決這個問題?
您使用的是什麼版本的Sails?你可以發佈你用來創建記錄的代碼嗎? – sgress454