简体   繁体   English

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

[英]In Mongoose/MongoDB, how to update properties in an array of an array

I have the following model: 我有以下模型:

An order model: 订单模型:

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}
});

A table model: 表模型:

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

A device model: 设备型号:

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}
};

A client model: 客户模型:

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}
});

A client has multiple tables. 一个客户端有多个表。 A table has multiple orders. 一个表有多个订单。

How can I update an order which is in an array of orders and itself is in an array of tables ? 如何更新订单数组中的订单,订单本身又是表格中的数组?

In another part of my code, I know how to do it when there is only one level of array...like that: 在我的代码的另一部分中,我知道当只有一个级别的数组时该怎么做……像这样:

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

But how to do it with nested arrays ?? 但是如何使用嵌套数组呢?

Thanks for your help, 谢谢你的帮助,

Patrice 帕特里斯

Use $push operator to update array entries. 使用$ push运算符更新数组条目。 Nested arrays can be accessed using the '.' 嵌套数组可以使用'。'访问。 notation as explained here 此处解释的符号

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM