如何在mongoose中保存json数据

时间:2021-10-25 06:44:00

This is my json data I want to save it in a mongoose database but I am confused how to design my mongoose schema.

这是我想要将它保存在mongoose数据库中的json数据,但我很困惑如何设计我的mongoose模式。

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.

这是我的Post模式,但我不知道如何实际设计它。

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
}]
});

1 个解决方案

#1


0  

You can store JSON to database directly:

您可以直接将JSON存储到数据库:

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!');
});

#1


0  

You can store JSON to database directly:

您可以直接将JSON存储到数据库:

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!');
});