MongoDB
 sql >> Base de données >  >> NoSQL >> MongoDB

impossible de mettre à jour un document via 'findById' et save() avec promesse

Envisagerait de décomposer l'opération en morceaux gérables. Dans ce cas, vous souhaitez mettre à jour le showTakenSeats champ avec les données de position du ticket de la nouvelle commande.

Tout d'abord, en utilisant l'attente asynchrone avec votre itinéraire express, vous devez enregistrer la commande et obtenir le document de commande créé. Créez un document avec les nouvelles places occupées, puis mettez à jour le document de l'émission à l'aide de findByIdAndUpdate méthode.

L'exemple suivant décrit ce qui précède :

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);
    }
});