"products"라는 MongoDB 컬렉션 인 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();
});
}
};
단일 데이터베이스 호출에서 컬렉션에 여러 제품을 삽입하려고 할 때 문제가 발생합니다.
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