首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法通过“findById”更新文档并承诺保存()

无法通过“findById”更新文档并承诺保存()
EN

Stack Overflow用户
提问于 2018-07-21 18:06:56
回答 2查看 640关注 0票数 1

我正在开发一个电影应用程序。通过猫鼬使用Node.js和mongodb。

当用户下订单时,我需要更新“显示”模型,并将最新的座位添加到“showTakenSeats”对象中。请注意,我需要将座位添加到“showTakenSeats”中,而不是替换所有的对象。

问题是,当我试图更新和保存节目-一切似乎都好。但最终它并没有成功地保存在DB中。

以下是代码:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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中。

db在“保存”之后:

有人知道问题出在哪里吗?

谢谢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-07-23 10:38:14

会考虑将操作分解成可管理的块。在本例中,您希望使用来自新订单的票证位置数据更新showTakenSeats字段。

首先,使用异步等待和快速路由,您需要保存订单并获得创建的订单文档。创建一个带有新座位的文档,然后使用findByIdAndUpdate方法更新显示文档。

下面的示例描述了上面的内容:

代码语言:javascript
复制
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);
    }
});
票数 2
EN

Stack Overflow用户

发布于 2018-07-21 19:42:25

看起来,您认为函数是按顺序执行的,但是当您按照像.then这样的承诺调用updateShow.save().then时,函数的执行不会等待并继续执行!这将导致下面的错误消息,在此您尝试在headers已经发送之后设置它们:

(节点:11476) UnhandledPromiseRejectionWarning:未处理的承诺>拒绝(拒绝id: 1):错误:不能在标题>发送后设置它们。(节点:11476) DEP0018 DeprecationWarning:未处理的承诺>拒绝被取消。将来,承诺拒绝>未处理的将使用非零退出>代码终止Node.js进程。

您可以在继续之前使函数asyncawait函数调用完成工作。

示例:

代码语言:javascript
复制
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
}

更多关于asyncawaithttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await的信息

这可能不是您的代码中唯一的错误,因此这将不会回答您的问题,但这个文本太长,不能发表评论。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51458777

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档