I have two types of JSON files that I want to insert to my mongodb database. I am using mongoose and nodejs to try that. How can I do it? I tried to look online for possible solutions, but I found nothing. Both of the JSON files have around hundred of inputs. So, inserting one by one not a good solution. I will give the sample of the data here for schema.
Type 1:
[
{
"name" : "Jonathan",
"lastName": "Smith"
},
{
"name" : "Simon",
"lastName": "Williams"
}
]
Type 2:
[
{
"id": 1,
"type": "fruit",
"inStock": [
{
"count": 15,
"items": [
{
"name": "apple",
"amount": 12
},
{
"name": "orange",
"amount": 3
}
]
}
},
{
"id": 2,
"type": "vegetable",
"inStock": [
{
"count": 18,
"items": [
{
"name": "carrot",
"amount": 10
},
{
"name": "lettuce",
"amount": 8
}
]
}
}
]
What would my schema be like? How do I parse my JSON file? An example code would be appreciated.
Ok, here is the code I wrote for this.
const fs = require("fs");
const mongoose = require('mongoose');
var assert = require('assert')
mongoose.connect('mongodb://localhost:27017/person'), { useNewUrlParser: true};
var personSchema = new mongoose.Schema({
name: String,
lastname: String
});
const Person = mongoose.model("Person", personSchema);
var data = fs.readFileSync('people.json');
let mydata = JSON.parse(data);
console.log(mydata);
Person.collection.insertMany(mydata, function(err) {
if(err){
console.log("There was an error");
console.log(err);
}else{
console.log("Success");
}
})
Console gives me Success. I have a db. But, I do not have a collection. What am I doing wrong here?
I think my problem is not that my code is not working. It is for some reason my code, even if it is a simple tutorial code will not save any collection to database. I do not know why.