MongooseError [ParallelSaveError]:无法并行保存()相同文档多次

时间:2019-12-18 12:36:33

标签: node.js mongodb mongoose promise

我遇到猫鼬和nodejs的问题。可能是我写错了代码或其他任何问题,请帮忙。这是我的控制器文件。 alldata.save给出[ParallelSaveError]

let createData = async function(req,res,next) {
    let body = req.body;
    let alldata = new League(body);
    let start_time = new Date().getTime();
    try {
         await Leaguecategories.find({})
                .then(async function(categories) {  
                    categories.forEach(async function(category) {
                      //here i am assigning foreign key
                        alldata.league_category_id = category._id;
                       await alldata.save(function(err, book){
                            if(err){
                                console.log(err);
                            }else{
                            res.send({status: 0, statusCode:"success", message: "Successfully inserted."})
                            }
                       });
                    })     
                })
    }
    catch (error){
        return res.send({status : 1 , statusCode : "error" , message : error.message})
    }
}

这是我的联赛类别模型

var mongoose = require('mongoose');


const league_categories = new mongoose.Schema({
    name: {
      type: String,
      required: true
    },
    active: {
      type: String,
      required: true
    },
    create_date: {
      type: Date,
      required: true,
      default: Date.now
    },
    league_type_id: {
      type: String,
      required: 'league_type',
      required:true
    }
  })

  module.exports = mongoose.model('Leaguecategories', league_categories)

这是我的联赛模特

var mongoose = require('mongoose');

    const league = new mongoose.Schema({
        title: {
            type: String,
            required: true
          },
          pool_price: {
              type: Number,
              required: true
          },
          entry_fee: {
              type: Number,
              required: true
          },
          total_spots: {
              type: Number,
              required: true
          },
          start_time: {
            type: Date,
            required: true
          },
          end_time: {
            type: Date,
            required: true
          },
          create_date: {
            type: Date,
            required: true,
            default: Date.now
          },
          active: {
            type: String,
            required: true
          },
          league_category_id: {
            type: String,
            ref: 'Leaguecategories',
            required:true
          }
    })

    module.exports = mongoose.model('League', league)

1 个答案:

答案 0 :(得分:1)

您每次必须创建League的新实例。像这样:

categories.forEach(async function(category) {
  //here i am assigning foreign key
  let alldata = new League(body);
  alldata.league_category_id = category._id;
  ...
});

建议:

您为什么同时使用async/await.then()?您只能使用其中之一。另外,还有其他一些问题。

  • awaitforEach内部不起作用
  • 您每次致电res.send()时都在呼叫.save()。这也可能最终会引发错误。

您可以像这样重构代码。

try {
  const categories = await Leaguecategories.find({});
  const promises = categories.map(function (category) {
    //here i am assigning foreign key
    let alldata = new League(body);
    alldata.league_category_id = category._id;
    return alldata.save();
  });

  await Promise.all(promises);

  res.send({ status: 0, statusCode: "success", message: "Successfully inserted." })
} catch (error) {
  return res.send({ status: 1, statusCode: "error", message: error.message });
}