猫鼬。如何更新包含在另一个数组中的数组元素? [英] Mongoose. How to update array element which contains in another array?

查看:96
本文介绍了猫鼬。如何更新包含在另一个数组中的数组元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这么复杂的架构,它有一个内部数组,每个数组元素包含一个更多的数组。但是如何更新二级数组内的数据。

I have so complicated schema which had an inner array each array element contains one more level array. But how to update data inside arrays of the second level.

我需要更新服务数组但是如何获取访问权限?我有_id的项目,线程编号,班次编号(可能只有3而这个数组不是由于三级数组很难)和服务名称。

I need to update services array but how to get access? I have _id of Item, thread number, shift number (Can be only 3 and this not array due to three level arrays it's so hard), and service name.

I需要像(伪代码)

getByItemId(id)
.getByThreadNumber(tNumber)
.getByShift(numberShift)
.getByServiceName(name)
.updateLogInCounter(newValCounter)

const itemSchema = new Schema({
    threads: [
        {
            number: {
                type: Number,
                requred: true
            },
            {
                firstShift: {
                    "someData": ... ,
                    "services": [
                        "name": {type: String}
                        "lastUpdate": {type: Date},
                        "logInCounter": {type: Number}
                    ]
                },
                secondShift: {
                    "someData": ... ,
                    "services": [
                        "name": {type: String},
                        "lastUpdate": {type: Date},
                        "logInCounter": {type: Number}
                    ]
                },
                thirdShift: {
                    "someData": ... ,
                    "services": [
                        "name": {type: String},
                        "lastUpdate": {type: Date},
                        "logInCounter": {type: Number}
                    ]
                }
            }
        }
    ]
})

也许这个数据结构不正确,这不可能?也许我需要创建许多集合?也许一些插件可以帮助我。或者这是正常的,如果是,如何获取我的目标数据?

Maybe this data structure incorrect and this impossible? Maybe I need to create many collections? Maybe some plugin helps me. Or it's normal, if yes how to get my target data?

推荐答案

您可以在3.6中使用以下代码

You can use below code in 3.6

使用计算属性名称动态传递班次编号。 $ [identifier] 位置运算符匹配线程号和服务名称,然后在线程服务内增加logInCounter。

Use computed property names to dynamically pass the shift number. $[identifier] positional operator to match thread number and service name followed by increment logInCounter inside service for thread.

var query = {'_id': id};
var inc = {'$inc':{'threads.$[t].' + [numberShift] + '.services.$[s].logInCounter':newValCounter}};
var arrayFilters = {arrayFilters: [{'t.number': tNumber, 's.name':name}]};
Item.findOneAndUpdate(query, inc, arrayFilters);

这篇关于猫鼬。如何更新包含在另一个数组中的数组元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆