Im pretty new to JavaScript and Mongoose. I ended with a bit weird designed JSON which I want to persist via mongoose.
This is an example of this JSON:
{name : "a_string", a1 : {something : 'a_number', something_else : 'a_number'}, a2 : {...} }
a1, a2 are variable (not always there are a1 neither a2, maybe there are others) something, something_else are variable also, can be different identifiers -they are properties-.
Maybe its my fault designing such a weird JSON but what would be the best way of defining a Schema for it?
I have various alternatives, neither convince me:
Schema {
myJSON : []
}
This is very ugly but now i could store my JSON as myJSON[0] = {name: "theName"...}. Ofc is the ugliest, but the most close I have found to my original data-structure.
another one
json Schema {
name: String,
parts: [part]
}
part Schema {
name : String,
props : [prop]
}
prop Schema {
name : String,
value : Numeric
}
This is more pretty BUT then I find several troubles, the final JSON will have many arrays and indirections I didnt have on the original one:
{name :"a_string", parts:[{name : "a1",
props : [{name : "something", value: 'a_number'}]},{...}]}
is there any way of removing all these annoying arrays from the Schema¿?
UPDATE:
Finally I have solved my issue because I could adapt my datamodel a bit:
var mySchema = new Schema({
name : String
, valid : Boolean
, parts : {}
});
Then the "props" contains all the JSON I want (except name is put outside). This is not the way I had in mind but it works fine (I think).
It looks like you are using mongoose embedded documents.
I'm not sure if embedded documents will always be wrapped inside arrays.
Following this mongoose documentation example :
var Comments = new Schema({
title : String
, body : String
, date : Date
});
var BlogPost = new Schema({
author : ObjectId
, title : String
, body : String
, date : Date
, comments : [Comments]
, meta : {
votes : Number
, favs : Number
}
});
A BlogPost can contains severals Comments, and Comments will be wrapped inside an array (just like your issue if i'm right).
What if you get rid of that array in the schema definition ?
Using Comments
instead of [Comments]
:
var BlogPost = new Schema({
author : ObjectId
, title : String
, body : String
, date : Date
, comments : Comments
, meta : {
votes : Number
, favs : Number
}
});
I can't try that now.
Otherwise, I have an idea using mongoose virtual attributes, if this doesn't work, let me know.
Edit
Using virtual attributes, you could do something like this :
BlogPost
.virtual('customComment')
.get(function() {
return this.comments[0];
});
This will return the first Comment entry object whithout the array.
var BlogPost = mongoose.model('BlogPost');
BlogPost
.find({ title: 'foo' })
.populate('comments')
.run(function (err, post) {
console.log(post.customComment); // returns the first comment without array
});
Not tested, this may contains typos.