Reputation: 1086
The JSON coming from an external web API looks like this:
[{matches:
[{
"match_something":"123",
"match_something_else":"Potato",
"match_events":
[{
"event_id":"42",
"event_desc":"redcard",
},
{
"event_id":"1",
..
}]
},
// more matches
So, match array with an event array within it for each match.
The relevant processing code looks like this:
_.each(matches, function(match) {
var results = new Results({
_id: match.match_id,
match_date: match.match_formatted_date,
ft_score: match.match_ft_score,
match_events:[]
});
events = match.match_events;
_.each(events, function(event) {
results.match_events.push({
_id:event.event_id,
match_id:event.event_match_id,
type:event.event_type,
team:event.event_team,
player:event.event_player,
});
});
results_array.push(results);
});
return results_array
This is the schema for the model (shortened for brevity):
var resultsSchema = new db.mongoose.Schema({
_id:Number,
match_date:String,
status:String,
...
match_events:[{
_id: Number,
match_id: Number,
type:String,
...
}]
});
And then, what I see from my database (mongo) once this completes is the following JSON (removed extra attributes for clarity):
[
{"_id":1931559, "ft_score":"[0-0]","__v":0,
"match_events":
["19315591","19315592","19315593","19315594"]},
Which just has me baffled. The ID's are correct, I checked against the server data. And the processing code is just creating an array of these ID's, instead of a JSON object for each event.
Shouldn't it be shown as:
..."match_events":
[{"_id:" "19315591", ...}]
Upvotes: 1
Views: 168
Reputation: 151092
Your schema definition is the problem here. Mongoose uses the "type" keyword to determine the datatype, so it thinks that "match_events" is an array of "String".
Declare like this instead:
var resultSchema = new Schema({
_id: Number,
status: String,
match_events: [{
_id: { type: Number },
type: { type: String }
}]
});
Or better yet like this:
var eventSchema = new Schema({
_id: Number,
type: String
});
var resultSchema = new Schema({
_id: Number,
status: String,
match_events: [eventSchema]
});
Upvotes: 3