Reputation: 36
This is my json data I want to save it in a mongoose database but I am confused how to design my mongoose schema.
data is { 'posts[0][commentId]': '0',
'posts[0][id]': '1',
'posts[0][postName]': 'hi',
'posts[0][img]': '',
'posts[0][postBy]': ' Neeraj',
'posts[1][commentId]': '0',
'posts[1][id]': '2',
'posts[1][postName]': 'hii',
'posts[1][img]': '',
'posts[1][postBy]': ' Neeraj',
'posts[1][comments][0][commentId]': '1',
'posts[1][comments][0][commentValue]': 'hlo how are u???',
'posts[1][comments][0][commentBy]': ' Neeraj',
'posts[1][comments][0][upCounter]': '5',
'posts[1][comments][0][downCounter]': '6' }
this is my Post schema but i dont know how to actually design it.
var postSchema=new Schema({
posts:[{
commentId: Number ,
comments : [{
commentBy : String,
commentId : String,
commentValue:String,
date:Date,
downCounter:Number,
upCounter:Number
}],
id:String,
img:String,
postBy:String,
postDate:Date,
postName:String
}]
});
Upvotes: 2
Views: 9003
Reputation: 41
You can just set your posts property as an Object in your mongoose schema and store the whole object.
Some thing like this :
var postSchema = new Schema({
posts: {
type: Object,
required: false //depends on whether the field is mandatory or not
}
});
Upvotes: 4
Reputation: 3576
You can store JSON to database directly:
var post_schema = mongoose.Schema({data : JSON});
var post_model = mongoose.model('collection_name', post_schema);
var newData = new post_model({data : <json_object>});
//saving json schema to mongodb
newData.save(function(err){
if (err) {
throw err;
}
console.log('INSERTED!');
});
Upvotes: 1