Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

145
Visualizações
Saving a new object with newly created reference IDs with Mongoose in NodeJS

I have a model called order that has a property orderItem. orderItem is of type id orderItem here's an extract of the schema.

const mongoose = require('mongoose');

const orderSchema = mongoose.Schema({
    orderItems: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'OrderItem',
        required: true
    }],
    shippingAddress1: {
        type: String,
        required: true,
    },

I create the order item first and then save the collection of order items as part of the new Order that I want to save. Done like this:

const orderItemsIds = Promise.all(req.body.orderItems.map(async orderItem => {
        let newOrderItem = new OrderItem({
            quantity: orderItem.quantity,
            product: orderItem.product
        })

        newOrderItem = await newOrderItem.save();

        return newOrderItem._id;
    }))

    try {
            
        const resolvedOrderItemsIds = await orderItemsIds;

        console.log(resolvedOrderItemsIds);

        let order = new Order({
            orderItems: resolvedOrderItemsIds,
            ...
        })

        // order = await order.save();
        order.save(function (err) {
            if(!order) {
                return res.status(400).send('The order cannot be created!');
            }
    
            return res.status(201).send({'message': 'Order Created', order});
        })
    

    } catch (error) {
        
    }

})

The OrderItems and Order are created and I get a response in PostMan that everything is created. I see results like this:

{
    "message": "Order Created",
    "order": {
        "orderItems": [
            "615562ab6c7cd7021c7e37f7",
            "615562ab6c7cd7021c7e37f8"
        ],
        "shippingAddress1": "21 sample street",
        "shippingAddress2": "Sample Bus Stop",
        "city": "Sample",
        "zip": "100001",
        "country": "Sample",
        "status": "Pending",
        "user": "6151a6d7f6d3b96060f0aec5",
        "_id": "615562ab6c7cd7021c7e37fb",
        "dateOrdered": "2021-09-30T07:09:31.493Z",
        "id": "615562ab6c7cd7021c7e37fb"
    }
}

What amuses me is that the Order does not get saved in MongoDB. Can I know what I am doing wrongly?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Turns out I was missing a required field when building the request body and there was no form of information about this after posting the request with the way I did it. I found out about my missing field when I saved the item like this:

await order.save().then(item => {
            return res.status(201).send({'message': 'Order Created', item});
        }).catch(err => {
            res.status(400).send({"message": 'The order cannot be created!', "error": err});
        })
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda