我需要从 Mongo 文档进行更改: 1. 数组内所有对象的一个属性 2. 数组内一个对象的一个属性。
我查看了 mongoose 文档,它说 exec() 使您的查询成为一个完整的 promise
。好吧,我不太明白,然后我尝试链接它们,但我不确定我是否做得好。
路由.js
router.patch("/internado/:id", (req, res, next) => {
const id = req.params.id;
const updateOps = {};
for (let prop in req.body) {
updateOps[prop] = req.body[prop];
}
User.update(
{ _id: id },
// this changes every element from object inside array
// already tested the command in postman
{ $set: { "datosAcademicos.internados.$[].activo": false } }
)
.exec()
.then(result => {
console.log(result);
res.status(200).json(result);
})
.catch(err => {
console.log(err);
res.status(500).json({ error: err });
});
User.update(
{ _id: id },
// pushs the new element to array. Also tested by itself on postman
{ $push: { "datosAcademicos.internados": updateOps } }
)
.exec()
.then(result => {
console.log(result);
res.status(200).json(result);
})
.catch(err => {
console.log(err);
res.status(500).json({ error: err });
});
});
问候
最佳答案
首先,这两个更新都会在某个时间结束,
更快的将返回并应答(res.send)并关闭连接。 当第二次更新完成时,res.send 已关闭并会引发异常。
你不能保证哪一个会先完成,如果顺序对你来说很重要,你应该真正链接然后而不是一个接一个地写它们。
如果这对你来说不重要,或者你只关心其中一个结果, 将其反射(reflect)在您的代码中。
所以如果你想链接然后(一个接一个):
// lets execute the first update
User.update(
{ _id: id },
{ $set: { "datosAcademicos.internados.$[].activo": false } }
).exec()
// now we wait for it to finish
.then(res => {
// do something with the first update ?
// possibly res.send if you did like
// now execute the other Update
return User.update(
{ _id: id },
{ $push: { "datosAcademicos.internados": updateOps } }
).exec()
})
.then(res2 => {
// possible res.send / other logging
res.send('done all updates');
})
.catch(err => {
console.log(err);
res.status(500).json({ error: err });
});
如果您想一起执行它们而不等待第一个:
Promise.all([
User.update(
{ _id: id },
{ $set: { "datosAcademicos.internados.$[].activo": false } }
).exec(),
User.update(
{ _id: id },
{ $push: { "datosAcademicos.internados": updateOps } }
).exec()
])
// wait for both of them to finish , order not guaranteed
.then(result => {
// result[0] - result for first update
// result[1] - result for second update ..
res.send(result);
})
.catch(err => {
console.log(err);
res.status(500).json({ error: err });
});
如果您只关心一个结果,但仍想执行这两个更新,只需将其反射(reflect)在您的代码中,这样您就不会调用 res.send 两次。
祝你好运
关于javascript - 无法将两个 api 调用链接到 mongo 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54610460/