Nodejs遍历字符串并保存到具有自动增量长度的mongodb中 [英] Nodejs loop through the string and save into mongodb with auto increment length

查看:109
本文介绍了Nodejs遍历字符串并保存到具有自动增量长度的mongodb中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在NodeJS中我有这样的字符串

In NodeJS I have string like this

"Package=Package&Qty=1&Price=123?Package=Package Two&Qty=3&Price=702?Package=Package Three&Qty=1&Price=199?Package=Package One&Qty=4&Price=852?";

我想用相应的套餐和价格保存每个数量。因此,假设我使用数量为3的Package 2,然后使用Package Two节省3次,Price将为702。

I want to save each Qty with corresponding Package and Price. So lets say I have Package Two with Qty 3 then it would save 3 times with Package Two and Price would be 702.

所以现在我的代码看起来像这样

So for now my code looks like this

const querystring = require('querystring');
const string = "Package=Package&Qty=1&Price=123?Package=Package Two&Qty=3&Price=702?Package=Package Three&Qty=1&Price=199?Package=Package One&Qty=4&Price=852?";
const items = string.split('?').filter(Boolean);
var TicketCountQuery = Ticket.count();
for(const query of items) {
    // Parse the query string of each group
    const { Package, Qty, Price } = querystring.parse(query);

    for(let i = 0; i < Number(Qty); i++) {
        console.log('Package Name ' + Package);
        console.log('Package Price ' + Price);

        TicketCountQuery.exec(function (e, count) {
          if( count !== '' ) {
            let TicketId = parseInt(count) + 1;
            console.log(TicketId);
            let ticketData = new Ticket({
              _id           : new mongoose.Types.ObjectId(),
              ticketid      : 'TKT '+ TicketId,
              packagename   : Package,
              price         : Price
            });

            ticketData.save((err) => {
              if( err ) {
                if( err.errors ) {
                  console.log('something went wrong');
                }
              }
              else {
                console.log('tickets saved');
              }
            });
          }
        });
      }
    }

这里的问题是它只是检查mongodb集合只是第一次。这就是为什么ticketid总是一样的。我希望每个插入都应该增加ticketid。但不知何故它不起作用。有人能告诉我怎么做吗?
任何帮助和建议都会非常明显。

Here the problem is it is just checking the mongodb collection only for the first time. That's why the ticketid is always same. I want that ticketid should be increment for each insert. But somehow its not working. So can someone tell me how to do this? Any help and suggestion will be really appreciable.

推荐答案

问题是你正在运行N个exec查询在保存任何故障单之前,这是因为 mongoose.exec 异步运行,因此所有查询都将返回相同的计数 。一个简单的解决方法是使用 async / await 。根据文档 .exec 如果没有提供回调,则返回一个承诺,因此我们可以等到执行完成后使用 await

The problem is that you're running the N exec queries before saving any ticket, this happens because the mongoose.exec runs asynchronously, so all the queries will return the same count. An easy fix is using async/await. According to the docs, .exec returns a promise if no callback is supplied, so we can easilly wait until the exec is done using await

const string = "Package=Package&Qty=1&Price=123?Package=Package Two&Qty=3&Price=702?Package=Package Three&Qty=1&Price=199?Package=Package One&Qty=4&Price=852?";

const qs = require('querystring');

async function processTickets(string) {

    const TicketCountQuery = Ticket.count();

    // We split the string into multiple valid query strings.
    // We strip the empty item due to the '?' at the end using .filter(Boolean)

    const items = string.split('?').filter(Boolean);

    // We loop through each group
    for(const query of items) {
        // Parse the query string of each group
        const { Package, Qty, Price } = qs.parse(query);

        for(let i = 0; i < Number(Qty); i++) {
            // We send the email here <Qty> times.
            console.log('Package Name ' + Package);
            console.log('Package Price ' + Price);

            try {
                // We wait until exec is done
                // No other tickets can be fetched/saved, preventing your problem
                const count = await TicketCountQuery.exec();

                if( count !== '' ) {

                    let TicketId = parseInt(count) + 1;

                    let ticketData = new Ticket({
                        _id: new mongoose.Types.ObjectId(),
                        ticketid: 'TKT ' + TicketId,
                        packagename: Package,
                        price: Price
                    });

                    // We save each ticket one at a time
                    // So the next one will have the correct ID.
                    await ticketData.save();
                    console.log('ticket saved');
                }

            } catch(e) {
                console.log('something went wrong', e);
            }
        }
    }

}

processTickets(string)
    .then(res => {
        console.log('Tickets processed!')
    })
    .catch(err => {
        console.error(err)
    })

这篇关于Nodejs遍历字符串并保存到具有自动增量长度的mongodb中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆