Reputation: 130
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.
Upvotes: 2
Views: 99
Reputation: 103455
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.
Upvotes: 2