我遇到了 Mongoose 和nodejs的问题。可能是我写错了代码或任何其他问题,请帮忙。这是我的 Controller 文件。 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)

最佳答案

您每次都必须创建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 });
    }
    

    关于node.js - MongooseError [ParallelSaveError] : Can't save() the same doc multiple times in parallel,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59392211/

    10-12 06:40