简体   繁体   中英

Creating a mongoose schema from a json

I am starting to play around with node.js, express, mongo and all that good stuff. I can't figure out how to define mongoose Schema for a JSON file like this:

[
  {
    "artist" : "Lorem",
    "profile-picture": "/lorem.jpg",
    "bio": "Lorem ipsum dolor sit amet, consectetur.",
    "songs": [
      {
        "id": 0,
        "name": "Lorem ipsum",
        "url": "/lorem.mp3",
        "length": 34,
        "rating": {
          "likes": 3,
          "likes-timestamps": [
            1436822318,
            1436822321,
            1436822334
          ]
        }
      }
    ]
  }
]

In every tutorial I came across, it's just too simplified to something like this:

MySchema = new Schema({
  name: String
});

And I am not sure about nesting those objects and arrays, etc. Thanks in advance.

Following the guidance from the Mongoose documentation on embedded documents, you can define a Schema like this:

var Song = new Schema({
    "id"      : Number,
    "name"    : String,
    "url"     : String,
    "length"  : Number,
    "rating"  : {
        "likes": Number,
        "likes-timestamps": [Number]
    }
});

var Artist = new Schema({
    "artist"            : String,
    "profile-picture"   : String,
    "bio"               : String,
    "songs"             : [Song]  
});

mongoose.model('Artist', Artist);

The songs key of your Artist documents will then be an instance of DocumentArray . This is a special subclassed Array that can deal with casting, and has special methods to work with embedded documents.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM