0

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

1 Answer 1

2

Use $push operator to update array entries. Nested arrays can be accessed using the '.' notation as explained here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.