这是保存" Orchard"的代码。记录。代码有效,但我想了解如何以良好的方式管理包含外键的数据(在本例中为" cropId),这是因为orchardId可能是无效值(例如,它无法&#39 ; t存在)所以我想了解如何处理外键约束的错误。
updatev2:我解决了捕获错误控制器的问题。现在唯一的问题是"错误:未实现"当我打印错误
OrchardService.add = function (req, res, next) {
var orchard = req.body;
db.Area.create({
name: orchard.name,
cropId: orchard.crop,
orchard: {}
}, {
include: [{model: db.Orchard, as: 'orchard'}]
})
.then(function (area) {
var coords = orchard.coordinates.map(function (coord) {
coord.areaId = area.id;
return coord;
});
db.AreaCoordinate.bulkCreate(coords)
.then(function () {
next({status: 200, status_message: 'OK', data: {orchard: area.orchardId}})
})
})
.catch(function (err) {
if (err instanceof Sequelize.ForeignKeyConstraintError) {
next({status: 501, status_message: 'Invalid Crop', error: err.message});
} else {
next({status: 500, status_message: 'Internal Server Error', error: err.message});
}
console.error(err);
})
TEST:
it('Add Orchard', function (done) {
chai.request(app)
.post('/orchard')
.send({
name: 'pantano',
crop: 1232,
coordinates: [
{latitude: '1', longitude: '3'},
{latitude: '2', longitude: '4'},
{latitude: '1', longitude: '5'}
]
})
.then(function (res) {
expect(res).to.have.status(200);
expect(res).to.have.header('content-type', 'application/json; charset=utf-8');
expect(res.body).to.be.an('object');
expect(res.body).to.have.status(200);
expect(res.body.status_message).to.equal('OK');
expect(res.body).to.have.property('data');
expect(res.body.data).to.have.property('orchard');
expect(res.body.data.orchard).to.be.an('number');
done();
})
.catch(function (err) {
done(err);
});
});
错误:
Error: Not Implemented
at Test.Request.callback (node_modules/superagent/lib/node/index.js:626:17)
at node_modules/superagent/lib/node/index.js:795:18
at IncomingMessage.<anonymous> (node_modules/superagent/lib/node/parsers/json.js:16:7)
at endReadableNT (_stream_readable.js:1047:12)
at _combinedTickCallback (internal/process/next_tick.js:102:11)
at process._tickCallback (internal/process/next_tick.js:161:9)