sql >> Base de Datos >  >> NoSQL >> MongoDB

no se puede actualizar un documento a través de 'findById' y save() con promesa

Consideraría dividir la operación en partes manejables. En este caso, le gustaría actualizar el showTakenSeats campo con los datos de posiciones de ticket de la nueva orden.

En primer lugar, al usar async await con su ruta expresa, debe guardar el pedido y obtener el documento de pedido creado. Cree un documento con los nuevos asientos ocupados y luego actualice el documento de espectáculo usando findByIdAndUpdate método.

El siguiente ejemplo describe lo anterior:

const express = require('express');
const router = express.Router();

const Order = require('../models/order.js');
const Show = require('../models/show.js');

router.post('/', async (req, res, next) => {
    try {
        /* create a new Order */
        const order = new Order(req.body);
        const newOrder = await order.save();

        /* create a document to use in the update with the following data structure:
            {
                'showTakenSeats.6-0': 5b53735ef7ce3d2cd4bbfee7,
                'showTakenSeats.6-1': 5b53735ef7ce3d2cd4bbfee7,
                'showTakenSeats.6-2': 5b53735ef7ce3d2cd4bbfee7 
            }

            Use the native reduce method on the array to create this 
        */
        const updatedSeats = newOrder.ticketPositions.reduce((acc, position) => {
            acc[`showTakenSeats.${position.join('-')}`] = newOrder._id;
            return acc;
        }, {});

        /* update the show document's embedded showTakenSeats 
           with the new properties from above 
        */
        const updateShow = await Show.findByIdAndUpdate(req.body._ShowId,
            { '$set': updatedSeats },
            { 'new': true }
        );

        res.json(updateShow);

    } catch (e) {
        /* this will eventually be handled by your error handling middleware */
        next(e);
    }
});