我有 2 个表:具有 m:m 关系的用户和 Material 。交集实体是journalMaterials。我正在尝试发送 POST 请求以插入 journalMaterials。此外,该表有 2 个属性:recycledQuantity 和 recycleDate。我尝试了一些东西,但是如果我插入一个不存在的 materialId,它不会给我“未找到”。
app.post('/users/:uid/materials/:mid', (req, res, next) => {
User.findById(req.params.uid)
.then((user) => {
if (user){
let journalMaterial = req.body
journalMaterial.userId = user.id
Material.findById(req.params.mid)
.then((material) => {
if (material){
journalMaterial.materialId = material.id
return JournalMaterial.create(journalMaterial)
}
else{
res.status(404).send('not found')
}
})}
else{
res.status(404).send('not found')
}
})
.then(() => {
if (!res.headers){
res.status(201).json('created')
}
})
.catch((err) => next(err))
})
最佳答案
我已经解决了。这是正确的代码。
app.post('/users/:uid/materials/:mid', (req, res, next) => {
const { uid, mid } = req.params;
Promise.all([
User.findById(uid),
Material.findById(mid)
])
.then(([user, material]) => {
if (user && material) {
let journalMaterial = req.body
journalMaterial.userId = user.id
journalMaterial.materialId = material.id
res.status(201).json('created')
return JournalMaterial.create(journalMaterial)
}
res.status(404).send('not found')
})
.catch(err => next(err));
})
关于node.js - POST 多对多 express 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49538707/