Reputation: 11064
I have sub document as in metrics. But I don't think I am saving correctly, because each document doesn't have metrics data correctly..instead it shows metrics: [ '[object Object]', '[object Object]', '[object Object]' ] and the data is impossible to access. This is really difficult to figure out since Mongoose doesn't give errors for this kind of stuff. If anyone could please tell me what is wrong.
EDIT: To make things more confusing, in the browser it shows that metrics has 3 arrays:
Object {cpuResult: Object}
cpuResult: Object
__v: 0
_id: "53b781d9fb272c4f44d8d1d8"
avaiable: true
metrics: Array[3]
0: "[object Object]"
1: "[object Object]"
2: "[object Object]"
length: 3
Here is my schema:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var CpuSchema = new Schema({
timeStamp : { type : Date, index: true },
avaiable : Boolean,
status : String,
metrics : [ { duration : String,
data : Number,
type : String,
unit : String
} ,
{ duration : String,
data : Number,
type : String,
unit : String
},
{ duration : String,
data : Number,
type : String,
unit : String
}
]
});
module.exports = CpuSchema;
Here is my save function:
function saveCpu(cpuResult) {
var cpu = new Cpu ({
timeStamp : cpuResult.timestamp,
avaiable : cpuResult.available,
status : cpuResult.status,
metrics : [ { duration : "15m",
data : cpuResult.metrics["15m"].data,
type: cpuResult.metrics["15m"].type,
unit: cpuResult.metrics["15m"].unit
},
{ duration : "5m",
data : cpuResult.metrics["5m"].data,
type: cpuResult.metrics["5m"].type,
unit: cpuResult.metrics["5m"].unit
},
{ duration : "1m",
data : cpuResult.metrics["1m"].data,
type: cpuResult.metrics["1m"].type,
unit: cpuResult.metrics["1m"].unit
}]
});
cpu.save(function (err, product, numberAffected) {
db_finish(err, product, numberAffected,
cpuResult, "cpuResult") });
Here is my data that gets inserted:
{ timestamp: 1404534588528,
available: true,
status: 'success',
metrics:
{ '15m': { data: 0.05, type: 'n', unit: 'unknown' },
'5m': { data: 0.01, type: 'n', unit: 'unknown' },
'1m': { data: 0, type: 'n', unit: 'unknown' } } }
Upvotes: 0
Views: 467
Reputation: 311865
When including a field named type
in a sub-doc of a Mongoose schema, you need to define its type using an object or it looks to Mongoose like you're declaring the type of the parent field.
So change your schema to:
var CpuSchema = new Schema({
timeStamp : { type : Date, index: true },
avaiable : Boolean,
status : String,
metrics : [ { duration : String,
data : Number,
type : {type: String},
unit : String
} ,
{ duration : String,
data : Number,
type : {type: String},
unit : String
},
{ duration : String,
data : Number,
type : {type: String},
unit : String
}
]
});
Upvotes: 2