В этом же посте я пытаюсь создать новый курс, а затем ВЫБЕРИТЕ этот курс с помощью метода findAll (). Я делаю это, потому что я хочу установить заголовок местоположения на правильный URI для курса, который был создан jsut. Для этого мне нужен доступ к его идентификатору, который генерируется автоматически. Проблема в том, что когда я вызываю метод findAll (), он говорит, что только что созданный курс не найден.
app.post('/api/courses', async (req, res) => {
try {
const newCourse = req.body;
await Course.create({
title: newCourse.title,
description: newCourse.description,
estimatedTime: newCourse.estimatedTime,
materialsNeeded: newCourse.materialsNeeded,
userId: 1
})
const course = await Course.findAll({
attributes: [newCourse.title]
})
res.location('/api/courses/' + course.id)
res.status(201);
}catch(error) {
console.warn(error);
}
})
app.get('/api/courses/:id', async (req, res) => {
try {
const courseRequest = req.params.id;
const course = await Course.findAll({
where: {
id: courseRequest
},
attributes: ['title', 'userId']
})
res.json({
course
});
}catch(error) {
console.error(error);
}
})
ОБНОВЛЕНИЕ ПОСЛЕ КОММЕНТАРИИ Наора Леви Я записал недавно созданный курс на консоль, и он вернул следующее:
Course {
dataValues:
{ id: 11,
title: 'Investing for beginners',
description: 'Learn to invest your money wisely',
estimatedTime: '3 weeks',
materialsNeeded: 'pen and paper',
userId: 1,
updatedAt: 2020-01-13T23:50:53.748Z,
createdAt: 2020-01-13T23:50:53.748Z },
_previousDataValues:
{ title: 'Investing for beginners',
description: 'Learn to invest your money wisely',
estimatedTime: '3 weeks',
materialsNeeded: 'pen and paper',
userId: 1,
id: 11,
createdAt: 2020-01-13T23:50:53.748Z,
updatedAt: 2020-01-13T23:50:53.748Z },
_changed:
{ title: false,
description: false,
estimatedTime: false,
materialsNeeded: false,
userId: false,
id: false,
createdAt: false,
updatedAt: false },
_modelOptions:
{ timestamps: true,
validate: {},
freezeTableName: false,
underscored: false,
paranoid: false,
rejectOnEmpty: false,
whereCollection: null,
schema: null,
schemaDelimiter: '',
defaultScope: {},
scopes: {},
indexes: [],
name: { plural: 'Courses', singular: 'Course' },
omitNull: false,
sequelize:
Sequelize {
options: [Object],
config: [Object],
dialect: [SqliteDialect],
queryInterface: [QueryInterface],
models: [Object],
modelManager: [ModelManager],
connectionManager: [ConnectionManager],
importCache: [Object] },
hooks: {} },
_options:
{ isNewRecord: true,
_schema: null,
_schemaDelimiter: '',
attributes: undefined,
include: undefined,
raw: undefined,
silent: undefined },
isNewRecord: false }
Executing (default): SELECT `Investing for beginners` FROM `Courses` AS `Course`;
{ SequelizeDatabaseError: SQLITE_ERROR: no such column: Investing for beginners
Он говорит мне, что курс, который я только что создал не существует, и я не уверен, почему.