简体   繁体   中英

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. Nested arrays can be accessed using the '.' notation as explained here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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