我遇到了这段代码的问题。 (使用节点,express,mongoose将文件保存到mongodb)
// We have an array that contains objects (365) of type 'Day' to be stored in mongodb.
// In my code this array contains data :-)
let arrDays = []
// Empty array to hold reference to the _id of the created days
let arrDaysID = [];
// Store all days in the 'arrDays' array to mongodb using mongoose
Day.create(arrDays, function(err, days){
if(err){
console.log("Something went wrong " + err)
} else {
// Iterate over every 'day' object in mongodb and add a reference to
// the _id of the 'day' object inside the 'year' object
days.forEach(function(day){
year.days.push(day._id);
year.save();
});
}
});
问题是,不是在'year'对象中添加每个_id引用一次,而是多次添加_id引用。代码运行完毕后,year.days数组中有大约140,000个引用,而定义只有365天...
欢迎任何提示或提示。
戴夫
答案 0 :(得分:1)
根据model.create
API的documentation,它是Shortcut for saving one or more documents to the database. MyModel.create(docs) does new MyModel(doc).save() for every doc in docs.
这意味着,您正在为create
方法中添加的每一天执行forEach循环,使其成为一个n * n复杂函数。
365 * 365 = 133225
大约等于140000条记录。
我认为这解释了这个问题。
编辑 - 更好的选择
根据mongoose insertMany API,Model.insertMany()
比Model.create because it only sends one operation to the server, rather than one for each document