node.js - 在 MongoDB 中,如何根据另一个字段有条件地更新具有不同值的文档
问题描述
我必须阅读多个文件。循环它们;如果文档有图像,我将状态设为“X”,如果没有,我将其设为“Y”。我已经这样实现了
const studies = await StudyModel.find({ status: 'uploading' });
studies.forEach(s => {
// Some more synchronous operations
const status = s.images ? 'X' : 'Y';
// non blocking update study call
StudyModel.Update({_id: study._id}, { status: studyStatus });
})
现在,如果在阅读研究之后和更新之前,用户在研究中添加图像会怎样。然后在 db 中有研究中的图像,状态应该是“X”,但代码会将其设为“Y”,因为它看不到新图像。这是一个罕见的情况,但已经发生了几次。
我正在寻找的是一种有条件地检查数据库中的图像并基于此进行更新的方法。这种东西。
StudyModel.Update({_id: id}, {$set: {status: {"$cond": {if: '$images', then: 'X', else: 'Y' } } } } )
有没有办法做到这一点?以及如何解决这样的问题?
解决方案
您可以使用 $exist 但有两个命令。
// image is exist
db.collection.updateMany(
{ status: 'uploading', image: { $exists: true } },
{ $set: { images: X} },
{
upsert: true,
}
)
// image is not exist
db.collection.updateMany(
{ status: 'uploading', image: { $exists: false } },
{ $set: { images: Y} },
{
upsert: true,
}
)
推荐阅读
- python - django 在 UpdateView 中提交多个表单
- android - 几次点击后音频文件停止在列表视图上播放?
- xslt - XSL - 用另一个字符替换管道
- google-cloud-kms - 从错误的文件创建密钥,我该如何修改它/解决这个问题?
- r - 具有多个 lm 函数的循环
- rabbitmq - 使用管理 REST API 更改现有 RabbitMQ 队列的最大优先级
- azure-webjobs - Azure Batch Job 顺序执行不起作用
- ios - WKWebView 可水平滚动
- matlab - 提取matlab/八度符号表达式的特定部分?
- python - 如何防止 gunicorn 工作者在尝试访问相同文件时崩溃