javascript - 在 Mongoose/MongoDB 中,如何更新数组的数组中的属性

标签 javascript arrays node.js mongodb mongoose

我有以下模型:

订购型号:

var order = new Schema({
content: [{
    product: {type: String, required: true},
    quantity: {type: Number},
    vatRate: {type: Number, required: true},
    price: {type: Number},
    deviceId: {type: String}
    }],
number: {type: Number},
tableId: {type: Schema.ObjectId, ref: 'Table'}
isAutomated: {type: Boolean, default: true},
createdAt: {type: Date, default: Date.now}
});

表格模型:

var table = {
tableNumber: {type: Number, default: 0},
status: {type: String, enum: ['Booked', 'Free', 'Active'], default: 'Free'},
order: [order]
};

设备型号:

var device = {
    deviceId: {type: String, required: true},
    status: {type: String, enum: ['Booked', 'Free', 'Active'], default:   'Free'},
    token: {type: String},
    tableId: {type: Schema.ObjectId, ref: 'Table'},
    isEnabled: {type: Boolean, default: true}
};

客户端模型:

var client = new Schema({
    information: {
        code: {type: String, required: true},
        name: {type: String, required: true}
},
account: {
    username: {type: String, required: true},
    password: {type: String, required: true},
    token: {type: String}
},
devices: [device],
tables: [table],
products: [product],
notifications: [notification],
createdAt: {type: Date, default: Date.now}
});

一个客户端有多个表。 一张表有多个订单。

如何更新位于订单数组中且其本身位于表数组中的订单?

在我的代码的另一部分,我知道当只有一层数组时如何做到这一点......就像这样:

 clientModel.findOneAndUpdate(
    {
        "information.code": clientCode,
        'devices.deviceId': deviceId
    },
    {
        $set: {
            'devices.$.status': device.status,
            'devices.$.tableId': device.tableId
        }
    },
    {
        new: true,
        select: {
            devices: {
                $elemMatch: {deviceId: deviceId}
            }
        }
    },

但是如何使用嵌套数组来做到这一点?

感谢您的帮助,

帕特里斯

最佳答案

使用 $push 运算符更新数组条目。可以使用“.”访问嵌套数组符号解释here

关于javascript - 在 Mongoose/MongoDB 中,如何更新数组的数组中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31168817/

相关文章:

javascript - 如何使历史 API 中的链接像真实的一样工作?

内联时未定义javascript变量

javascript - 如何从特定记录访问对象中的嵌套数组?

php - 比较两个数组并获得所有差异

php - MySQL 返回 PHP 关联数组 - 但我无法访问数组数据

node.js - watch 可以与 Jade 搭配使用吗?

javascript - 在 Raspberry Pi Zero 上,puppeteer 在超时后挂起

javascript - 访问 javascript 中的 props

node.js - “submodule”似乎是一个 git 命令,但我们无法执行它

javascript - Nodejs 无法 TCP/解析长 JSON 文件