gpt4 book ai didi

node.js - MongooseError [并行保存错误] : Can't save() the same doc multiple times in parallel

转载 作者:太空宇宙 更新时间:2023-11-03 23:51:15 24 4
gpt4 key购买 nike

我遇到了 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 中不起作用
  • 每次调用 .save() 时,都会调用 res.send()。这也可能最终引发错误。

您可以像这样重构代码。

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 [并行保存错误] : Can't save() the same doc multiple times in parallel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59392211/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com