MongoDBコレクションである「products」というSails.jsモデルがあります。モデルでは、 'YYMMDD-count`の形式で' 170921-00001 'のような一意のproductIdを生成するbeforeCreate()
フックを持っています。ここで、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();
});
}
};
1つのデータベースコールで複数の製品をコレクションに挿入しようとすると、この問題が発生します。私は次のエラーを取得する:
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
を計算する前にドキュメントが挿入されているためですか?これをどうすれば解決できますか?
あなたはどのバージョンのセイルを使用していますか?レコードを作成するために使用しているコードを投稿することはできますか? – sgress454