简体   繁体   English

MongoDB中JSON数组无序保存使用mongoose的.save()方法

[英]JSON array saves in disorder in MongoDB using the .save() method of mongoose

I need to save a long JSON array in a collection in a free MongoDB database.我需要在一个免费的 MongoDB 数据库的集合中保存一个长 JSON 数组。

For that I connect to my database via mongoose then I make a for loop which will read each JSON of my array and save it with the good model in the good collection thanks to the save() method of mongoose .为此,我通过 mongoose 连接到我的数据库,然后我创建了一个for循环,该循环将读取我的数组的每个 JSON,并借助mongoosesave()方法将其与良好集合中的良好模型一起保存。 I make this connection in an application that uses node and the express framework.我在使用 node 和 express 框架的应用程序中建立了这种连接。

This is the following code, which I tried to simplify, that does this:这是我试图简化的以下代码:

 const data = [
  {
    "numero": 1531,
    "annee": 2022,
    "date": "22/05/2022",
    "premier_cas": 10
  },
  {
    "numero": 1532,
    "annee": 2022,
    "date": "29/05/2022",
    "premier_cas": 15
  }
//MANY THOUSANDS OF OBJECT
];

const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const db = {};
db.mongoose = mongoose;
db.result = require("./result.model");

const Result = db.result;

db.mongoose
  .connect(process.env.MONGODB_URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true
  })
  .then((client) => {
    console.log("Successfully connect to MongoDB.");
    addResultToCollection();
  })
  .catch(err => {
    console.error("Connection error", err);
    process.exit();
  });

function addResultToCollection() {
  Result.estimatedDocumentCount(async (err, count) => {
    if (!err && count === 0) {
      for (let i = 0; i < data.length; i++) {
        await createAndSaveOneResult(data[i], i);
      }
    } else if (count !== 0) {
      console.log("Results have already been created!");
    }
  });
}

async function createAndSaveOneResult(json, counter) {
  new Result({
    numero: json.numero,
    annee: json.annee,
    date: json.date,
    premier_cas: json.cas
  }).save(err => {
    if (err) {
      console.log("error", err);
    }
    console.log("Results %d a été créé", counter);
  });
}

My model Result is the following :我的模型结果如下:

const mongoose = require('mongoose');

const Result = mongoose.model(
    "Result",
    (new mongoose.Schema({
        numero: {
            type: Number,
            required: 'This field is required'
        },
        annee: {
            type: Number,
            required: 'This field is required'
        },
        date: {
            type: String,
            required: 'This field is required'
        },
        premier_cas: {
            type: Number,
            required: 'This field is required'
        },
    })).index({ "$**": 'text' })
);

module.exports = Result;

This code allows me to connect to my database and save the thousands of JSONs that are contained in my array.此代码允许我连接到我的数据库并保存包含在我的数组中的数千个 JSON。 The problem is that the recording is not done in the right order, when I display the number of the object created in my terminal at the time of its creation I get this :问题是录制没有按正确的顺序完成,当我显示创建时在终端中创建的对象的编号时,我得到了这个:

...
Results 947 a été créé
Results 942 a été créé
Results 988 a été créé
Results 995 a été créé
Results 994 a été créé
Results 1000 a été créé
Results 997 a été créé
Results 996 a été créé
Results 987 a été créé
Results 990 a été créé
Results 991 a été créé
Results 989 a été créé
Results 992 a été créé
Results 993 a été créé
Results 1003 a été créé
Results 1001 a été créé
Results 999 a été créé
Results 998 a été créé
Results 1004 a été créé
Results 1002 a été créé
Results 1007 a été créé
Results 986 a été créé
Results 1020 a été créé
Results 1011 a été créé
...

When I look at the new objects registered in my MongoDB collection they are also in disorder,, so it's not a timing issue because of the local console.log() which would fail to keep up with the saving in MongoDB.当我查看在我的 MongoDB 集合中注册的新对象时,它们也是无序的,因此这不是时间问题,因为本地console.log()无法跟上 MongoDB 中的保存速度。

To solve this problem and put my objects in the right order I tried to use async/await logic to wait for the save() method to be performed before saving the next object, this is what I did in the code above.为了解决这个问题并将我的对象按正确的顺序放置,我尝试使用 async/await 逻辑来等待save()方法在保存下一个对象之前执行,这就是我在上面的代码中所做的。 But the problem remained the same.但问题仍然存在。

I also tried to put a setTimeOut() in my for loop to wait two seconds between each object registration, this is the following code but the problem remained the same.我还尝试在我for循环中放置一个setTimeOut()以在每个对象注册之间等待两秒钟,这是以下代码,但问题仍然存在。

db.mongoose
  .connect(process.env.MONGODB_URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true
  })
  .then((client) => {
    console.log("Successfully connect to MongoDB.");
    addResultToCollection();
  })
  .catch(err => {
    console.error("Connection error", err);
    process.exit();
  });

function addResultToCollection() {
  Result.estimatedDocumentCount(async (err, count) => {
    if (!err && count === 0) {
      for (let i = 0; i < data.length; i++) {
        setTimeout(() => {
          new Result({
            numero: data[i].numero,
            annee: data[i].annee,
            date: data[i].date,
            premier_cas: data[i].premier_cas
          }).save(err => {
            if (err) {
              console.log("error", err);
            }
            console.log("Results %d a été créé", i);
          });
        }, "2000")
      }
    } else if (count !== 0) {
      console.log("Results have already been created!");
    }
  });
}

If anyone knows how to fix this problem and get the objects in the array to save in the right order it would be a great help.如果有人知道如何解决这个问题并让数组中的对象以正确的顺序保存,那将是一个很大的帮助。

I found my problem, I was using the wrong mongoose method.我发现了我的问题,我使用了错误的猫鼬方法。 save() saves one document and insertMany() saves multiple documents. save()保存一个文档, insertMany()保存多个文档。

The code that works:有效的代码:

const db = require("./models");
const Role = db.role;
const Result = db.result;
db.mongoose
  .connect(process.env.MONGODB_URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true
  })
  .then((client) => {
    console.log("Successfully connect to MongoDB.");
    addResultToCollection();
  })
  .catch(err => {
    console.error("Connection error", err);
    process.exit();
  });
 
function addResultToCollection() {
  Result.estimatedDocumentCount(async (err, count) => {
    if (!err && count === 0) {
      Result.insertMany(data)
        .then(function () {
          console.log("Data inserted")
        }).catch(function (error) {
          console.log(error)
        });
    } else if (count !== 0) {
      console.log("Results have already been created!");
    }
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM