【发布时间】:2020-04-05 10:31:59
【问题描述】:
我使用的是 Mongo 版本 2.2.33。这是一个大型项目,主要是遗留代码,更新内容不取决于我。如果我有更新版本的 Mongo,我会使用 $indexOfArray,但既然我不能,我怎样才能实现同样的目标?
这是我在意识到我们使用的是什么版本的 mongo 之前编写的代码:
exports.getActionHistoryIndex = function (historyArray, deviceId, cb) {
db.actions.aggregate({$indexOfArray: {historyArray, deviceId}}, function (err, index) {
if (err) {
return cb(err)
} else {
return cb(null, index)
}
})
}
当我调用函数时,像这样:
actionRepo.getActionHistoryIndex(action.history, device._id, (err, res) => {
if (err) console.log(err)
console.log(res)
})
我收到此错误,因为 $indexOfArray 在 3.8 之后可用,我认为:
name: 'MongoError',
message: 'Unrecognized pipeline stage name: \'$indexOfArray\'',
ok: 0,
errmsg: 'Unrecognized pipeline stage name: \'$indexOfArray\'',
code: 40324,
codeName: 'Location40324' }
undefined
有没有简单的方法来实现这一点?基本上,问题是我有一个 db 集合,其中包含一个包含对象的数组。我需要能够在数组中的对象中搜索某个_id,然后编辑同一对象中的另一个属性。所以我的计划是获取正确对象的索引,然后使用索引更新需要更改的属性。
感谢任何帮助。
编辑:这是来自action 集合的示例文档。
_id : ObjectId('ABC')
history: [Array]
0: {Object}
device_id: ObjectId("123")
triggered: false
1: {Object}
device_id: ObjectId("456")
triggered: true
收到用户输入后,我需要更改 triggered 布尔值。我有操作文档 ObjectId,并且我有对应于 history 数组中不同对象的 device_id。所以我正在寻找允许我更改 triggered 布尔值的查询/更新。
编辑2: 这是我阅读答案后的功能:
exports.updateHistory = function (action, deviceId, triggered, cb) {
console.log(action._id + ' || action._id')
console.log(deviceId + ' || deviceId')
console.log(triggered + ' || triggered')
db.actions.updateOne(
{_id: action._id, 'history.device_id': deviceId},
{$set: { 'history.$.triggered': triggered }},
{w: 1},
function (err, results) {
if (err) {
return cb(err)
}
return cb(null, results)
})
}
所有日志语句都是正确的,我没有收到任何错误,但我的文档根本没有更改。对于三个不同的action 文档,此函数被调用了三次。所有 3 的 triggered 值当前为 false。此函数运行时,传入的triggered 值为true,但它不会更新文档。有什么建议吗?
【问题讨论】:
-
您不必为了更新特定对象中的特定字段而获取数组中对象的索引,您可以使用 mongoDB 中的位置运算符来完成,请给我们示例文档&需要o / p有人可以帮助您查询!
-
我已经用示例文档更新了我的答案,以及我想要完成的工作。谢谢。
标签: arrays node.js mongodb indexing