Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript MongoDB与mongoose会话问题_Javascript_Mongodb_Mongoose_Transactions - Fatal编程技术网

Javascript MongoDB与mongoose会话问题

Javascript MongoDB与mongoose会话问题,javascript,mongodb,mongoose,transactions,Javascript,Mongodb,Mongoose,Transactions,所以我的代码有问题。我正在尝试编写一个方法,为使用MongoDb中的事务的用户添加一个事务 const { transactionModel } = require("../../models/index"); const { getBalance } = require("../../helpers/index"); const mongoose = require("mongoose"); module.exports = asy

所以我的代码有问题。我正在尝试编写一个方法,为使用MongoDb中的事务的用户添加一个事务

const { transactionModel } = require("../../models/index");
const { getBalance } = require("../../helpers/index");
const mongoose = require("mongoose");

module.exports = async (req, res, next) => {
  const session = await mongoose.startSession();
  const transactionOptions = {
    readPreference: "primary",
    readConcern: { level: "local" },
    writeConcern: { w: "majority" },
    j: false,
  };

  try {
    await session.withTransaction(async () => {
      const { walletId } = res.locals.user;
      const { longitude, latitude, merchant, amountInCents } = req.body;
      const balance = await getBalance(walletId, session);
      console.log({ balance, amountInCents });

      if (balance + amountInCents < 0) {
        console.log("not enoght money");
        throw new Error("LOGOUTERROR");
      }
      const actualBalance = balance + amountInCents;
      const createdAt = Date.now();
      const newMerchant = await transactionModel.create(
        [
          {
            walletId,
            longitude,
            latitude,
            merchant,
            amountInCents,
            createdAt,
          },
        ],

        { session }
      );
      await session.commitTransaction();
      console.log({ newMerchant });
      console.log({ actualBalance });
      return res.status(201).json({
        walletId,
        longitude,
        latitude,
        merchant,
        amountInCents,
        createdAt,
        balance: actualBalance,
      });
    }, transactionOptions);
  } finally {
    await session.endSession();
    session.endSession();
  }
};


问题是,我使用getBalance方法获得相同的平衡,但希望在每个请求上获得不同的平衡。 如何解决这个问题?谢谢你们的帮助,伙计们



const { userModel, transactionModel, tokenModel } = require("../models/index");

module.exports = async (walletId, session) => {
  try {
    const result = await transactionModel
      .aggregate(
        [
          { $match: { walletId } },
          { $group: { _id: null, balance: { $sum: "$amountInCents" } } },
        ]
        // { readConcern: { level: "local" } }
      )
      .session(session);
  

    if (result.length < 1 || result == undefined) {
      return 0;
    } else {
      return result[0].balance;
    }
  } catch (err) {
    console.log(err);
  }
};
const axios = require("axios");

axios.defaults.baseURL = "http://localhost:3000";
axios.defaults.headers.common.Authorization = `Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVmN2JhYjZlMGQyMTMwNzM0YmEwNGU2OSIsImlhdCI6MTYwMjA5NjM0MiwiZXhwIjoxNjAyMTgyNzQyfQ.WtDWh1zQX3NbJAsJYWpW_naA1DKkopoPcfT63OSXIlo`;
const money = {
  longitude: "-100",
  latitude: "-100",
  merchant: "Bed",
};

async function run() {
  const [
    { data: a },
    { data: b },
    { data: c },
    { data: d },
    { data: e },
    { data: f },
  ] = await Promise.all([
    axios.put("/transaction", { ...money, amountInCents: 100 }),
    axios.put("/transaction", { ...money, amountInCents: 200 }),
    axios.put("/transaction", { ...money, amountInCents: -400 }),
    axios.put("/transaction", { ...money, amountInCents: 100 }),
    axios.put("/transaction", { ...money, amountInCents: 200 }),
    axios.put("/transaction", { ...money, amountInCents: -600 }),
  ]);
  console.log(a, b, c, d, e, f);
}

run().catch(console.log);