简体   繁体   中英

How do I push to an array within an array in a collection with mongoose?

I have a User schema created with Mongoose that holds a customer array, and inside that customer array there is another fleet array. I have figured out how to push to the customer array within the User schema , however I can not figure out how to loop through the customers, find the customer via id or name, and then push data into the fleet array.

Here is my User schema :

const mongoose = require('mongoose');

const UserSchema = new mongoose.Schema({
    username: {
        type: String,
        default: ''
    },
    password: {
        type: String,
        default: '',
    },
    registerDate: {
        type: Date,
        default: Date.now()
    },
    customer: [{
        name: {
            type: String,
            default: '',
        },
        email: {
            type: String,
            default: 'No email addresses found',
        },
        fleet: [{
            unitType: {
                type: String,
                default: 'No type selected',
            },
            unitNumber: {
                type: String,
                default: 'No unit number provided',
            },
            vinNumber: {
                type: String,
                default: 'No vin number provided'
            },
        }]
    }]
});

module.exports = mongoose.model('User', UserSchema);

I was able to figure out how to push a new customer into the customer array no problem. My problem is I do not get how I can loop through the customer array, and once I find the customer that I need, push data into the fleet array. I am really just stumped on how to word my Google search! Hopefully this is detailed enough, and please let me know if you need to see any other code.

You need to use positional '$' operation. Read here

UserSchema.update(
    {'customer.email':'xyz@email.com'},
    {
        $push:{
            'customer.$.fleet':<fleet object>
        }
    },function(err,result){

    })

--- OR ---

UserSchema.update(
    {'customer.email':'xyz@email.com'},
    {
        $set:{
             'customer.$.fleet':[fleet array]
        }
    },function(err,result){

    })

Hope this helps.

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