I'm faced with the challenge of storing a lengthy JSON array in a free MongoDB database collection.
To achieve this, I establish a connection to my database using mongoose and then utilize a for
loop to iterate through each JSON object in the array. These objects are saved appropriately in the corresponding collection thanks to the save()
method provided by mongoose
. The entire process takes place within an application that runs on node.js and employs the express framework.
The code snippet below illustrates how I accomplish this task:
const data = [
{
"numero": 1531,
"annee": 2022,
"date": "22/05/2022",
"premier_cas": 10
},
{
"numero": 1532,
"annee": 2022,
"date": "29/05/2022",
"premier_cas": 15
}
//THOUSANDS OF OBJECTS
];
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 has been created", counter);
});
}
The model for my Result is defined as follows:
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;
Despite implementing measures like async/await logic and introducing delays with setTimeOut()
, the issue persists wherein the objects are not being saved in the correct order both in the terminal logs and the MongoDB collection entries.
If anyone has insights or solutions to rectify this problem and ensure orderly saving of the array objects, your guidance would be greatly appreciated.