无法通过更新的文档“findById”并保存()的承诺(can not update a docum

2019-09-28 04:27发布

我要建一个电影院应用程序。 通过猫鼬如何使用Node.js和MongoDB。

当用户发出命令,我需要更新“显示”模型,并添加奉命“showTakenSeats”对象最新的席位。 请注意,我需要的席位添加到“showTakenSeats”,而不是代替所有的对象。

问题是,当我尝试更新和保存的节目 - 一切似乎确定。 但最终它不会成功在数据库中保存。

下面是代码:

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

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

router.post("/", (req, res) => {
    if (!req.body) {
        return res.sendStatus(400);
    }
    let order = new Order(req.body);
    order.save().then(newOrder => {
        console.log("Order saved successfully");
        Show.findById(req.body._ShowId).then(updateShow => {
            console.log('we got the show');
            console.log(newOrder.ticketsPositions);
            console.log("updateShow before any changes");
            console.log(updateShow);
            newOrder.ticketsPositions.forEach(element => {
                updateShow.showTakenSeats[element[0] + "-" + element[1]] = newOrder._id;
            });
            console.log("updateShow after adding new seats");
            console.log(updateShow);
            updateShow.save().then((updateShowSaved) => {

                console.log('updated the last order seats at the Show seats map')
                console.log(updateShowSaved);
                //res.json(updateShowSaved);
            }, err => {
                console.log(err);
                //res.send(err);
            });
            res.json(updateShow);
        }, err => {
            console.log(err);
        });
        res.json(newOrder);
    }, err => {
        res.send(err);
    });
});


module.exports = router;

的console.log:

Order saved successfully
we got the show
[[6,0],[6,1],[6,2]]
updateShow before any changes
{ _id: 5b5203bfcbb3a311c0911b8f,
  _MovieId: 5b45faa4a53b0c05f8959262,
  _TheaterId: 5b3dfeb217bc8c23f0e7ec3f,
  date: '2018-07-22',
  time: '22:00',
  dateTime: 2018-07-22T19:00:00.000Z,
  showTakenSeats:
   { '0-14': 5b52186a7feaac1028ec592f,
     '5-0': 5b530e6dc7d3ed280427145a,
     '5-1': 5b530e6dc7d3ed280427145a,
     '5-2': 5b530e6dc7d3ed280427145a },
  __v: 0,
  movieInfo: null,
  theaterInfo: null,
  id: '5b5203bfcbb3a311c0911b8f' }
updateShow after adding new seats
{ _id: 5b5203bfcbb3a311c0911b8f,
  _MovieId: 5b45faa4a53b0c05f8959262,
  _TheaterId: 5b3dfeb217bc8c23f0e7ec3f,
  date: '2018-07-22',
  time: '22:00',
  dateTime: 2018-07-22T19:00:00.000Z,
  showTakenSeats:
   { '0-14': 5b52186a7feaac1028ec592f,
     '5-0': 5b530e6dc7d3ed280427145a,
     '5-1': 5b530e6dc7d3ed280427145a,
     '5-2': 5b530e6dc7d3ed280427145a,
     '6-0': 5b53735ef7ce3d2cd4bbfee7,
     '6-1': 5b53735ef7ce3d2cd4bbfee7,
     '6-2': 5b53735ef7ce3d2cd4bbfee7 },
  __v: 0,
  movieInfo: null,
  theaterInfo: null,
  id: '5b5203bfcbb3a311c0911b8f' }
(node:11476) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Can't set headers after they are sent.
(node:11476) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
updated the last order seats at the Show seats map
{ _id: 5b5203bfcbb3a311c0911b8f,
  _MovieId: 5b45faa4a53b0c05f8959262,
  _TheaterId: 5b3dfeb217bc8c23f0e7ec3f,
  date: '2018-07-22',
  time: '22:00',
  dateTime: 2018-07-22T19:00:00.000Z,
  showTakenSeats:
   { '0-14': 5b52186a7feaac1028ec592f,
     '5-0': 5b530e6dc7d3ed280427145a,
     '5-1': 5b530e6dc7d3ed280427145a,
     '5-2': 5b530e6dc7d3ed280427145a,
     '6-0': 5b53735ef7ce3d2cd4bbfee7,
     '6-1': 5b53735ef7ce3d2cd4bbfee7,
     '6-2': 5b53735ef7ce3d2cd4bbfee7 },
  __v: 0,
  movieInfo: null,
  theaterInfo: null,
  id: '5b5203bfcbb3a311c0911b8f' }

当我检查文件中的DB后,我运行的代码,新的座椅没有被保存在数据库中。

“保存”后,DB:

任何人都知道是什么问题?

谢谢

Answer 1:

会考虑操作分解成可管理的块。 在这种情况下,你要更新的showTakenSeats与新秩序的票位置的数据字段。

首先,使用异步得到您的明确路线等待你需要保存的顺序,并获得创建订单文档。 创建一个新的拍摄席位的文件,然后使用更新的电视剧文档findByIdAndUpdate方法。

以下示例描述以上:

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


Answer 2:

它看起来像你认为的功能按顺序执行,但是当你打电话.then像一个承诺updateShow.save().then该函数的执行不等待,继续! 这会导致下面,你尝试设置错误消息headers ,他们已经被发出后:

 > (node:11476) UnhandledPromiseRejectionWarning: Unhandled promise > rejection (rejection id: 1): Error: Can't set headers after they are > sent. (node:11476) [DEP0018] DeprecationWarning: Unhandled promise > rejections are deprecated. In the future, promise rejections that are > not handled will terminate the Node.js process with a non-zero exit > code. 

你可以让你的函数asyncawait函数调用,然后再继续完成工作。

例:

router.post("/", async (req, res) => {
    let order = new Order(req.body);
    await order.save(); // if this fails an exception is thrown
    console.log('order is saved') // statement is executed after order is saved
}

更多关于asyncawait : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await

这可能是不是在你的代码的唯一的错误,因此这不会回答你的问题,但这个文本是注释太长。



文章来源: can not update a document via 'findById' and save() with promise