Add subdocuments to document - mongoose

1

Good evening! I have the following document:

{ 
    "_id" : ObjectId("5b21a4332a5e3333cc64a12f"), 
    "nome" : "João", 
    "sobrenome" : "Barbosa", 
    "cpf" : "12345678910", 
    "senha" : "Fabet@1010", 
    "viagem" : [
        {
            "empresa_origem" : "BRF", 
            "cidade_origem" : "Concórdia", 
            "uf_origem" : "SC", 
            "pais_origem" : "Brasil", 
            "empresa_destino" : "Santiago Foods", 
            "cidade_destino" : "Santiago", 
            "uf_destino" : "CH", 
            "pais_destino" : "Chile", 
            "peso" : "20000", 
            "carga" : "Queijo", 
            "placa_caminhao" : "MMM-9999", 
            "_id" : ObjectId("5b21a4332a5e3333cc64a130")
        }
    ], 
    "__v" : NumberInt(0)
}

Notice that the subdocument vaigem exists.

In the example above, there is a user's registration and a trip. I would like to register more trips in this same user, as follows:

{ 
    "_id" : ObjectId("5b21a4332a5e3333cc64a12f"), 
    "nome" : "João", 
    "sobrenome" : "Barbosa", 
    "cpf" : "12345678910", 
    "senha" : "Fabet@1010", 
    "viagem" : [
        {
            "empresa_origem" : "BRF", 
            "cidade_origem" : "Concórdia", 
            "uf_origem" : "SC", 
            "pais_origem" : "Brasil", 
            "empresa_destino" : "Santiago Foods", 
            "cidade_destino" : "Santiago", 
            "uf_destino" : "CH", 
            "pais_destino" : "Chile", 
            "peso" : "20000", 
            "carga" : "Queijo", 
            "placa_caminhao" : "MMM-9999", 
            "_id" : ObjectId("5b21a4332a5e3333cc64a130")
        },
        {
            "empresa_origem" : "BRF", 
            "cidade_origem" : "Capinzal", 
            "uf_origem" : "SC", 
            "pais_origem" : "Brasil", 
            "empresa_destino" : "Santiago Foods", 
            "cidade_destino" : "Santiago", 
            "uf_destino" : "CH", 
            "pais_destino" : "Chile", 
            "peso" : "22000", 
            "carga" : "Carne Suína", 
            "placa_caminhao" : "MMM-9999", 
            "_id" : ObjectId("5b21a4332a5e3333cc64a131")
        }
    ], 
    "__v" : NumberInt(0)
}

Is it possible? How can I do this using mongoose? I know I should use the _id of user "John" as parameter.

    
asked by anonymous 14.06.2018 / 01:41

1 answer

3

Use the $push operator:

Collection.findByIdAndUpdate(id, { $push: {viagem: OBJETO } }, options, callback)  
    
14.06.2018 / 01:45