I have this json:
{
"data": [
"id": "1",
"name": "Sample test",
"description": "this is a sample test",
"category": "tests",
"points": 100,
"startDate":"2018-02-15 00:00:00",
"endDate":"2018-02-22 00:00:00",
"isActive":true,
"alreadyAnswered":false,
"questions":[
{
"id": 1,
"text": "What is your name",
"type": "text",
},
{
"id": 2,
"text": "What is your favorite color",
"type": "select",
"options": [
{
"id": 1,
"text": "Red",
"value": "red"
},
{
"id": 2,
"text": "Blue",
"value": "blue"
}
]
}
]
]
}
I need to create this json into mongo database so I can get it via my node application.
This is my current schema:
let TestSchema = new Schema({
id: Number,
name: String,
description: String,
category: String,
points: Number,
startDate: Date,
endDate: Date,
isActive: Boolean,
alreadyAnswered: Boolean
});
My greatest problem is I don't know how to add other objects into my schema to replicate the json, in MySQL I would do it with a hasmany relationship and add the correspondent id into the questions and options, but in this case I need to do via Mongo(create the json and get it via a route).
How can I do that programatically? Thanks in advance.
Working with save() save() is a method on a Mongoose document. The save() method is asynchronous, so it returns a promise that you can await on. When you create an instance of a Mongoose model using new , calling save() makes Mongoose insert a new document.
Mongoose | save() Function The save() function is used to save the document to the database. Using this function, new documents can be added to the database.
data: [
id: String, //or number, whatever you need
name: String,
description: String,
category: String,
points: Number,
startDate: Date,
endDate: Date,
isActive: Boolean,
alreadyAnswered: Boolean,
questions:[{
id: String, //or again, number
text: String,
type: String,
options: [
{
id: String, //or number
text: String,
value: String
}
]
}
]
]
This should be schema for this JSON
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With