JulianOliveira JulianOliveira - 1 month ago 18
Node.js Question

moongose: reading data from mongodb with nodejs

I'm using nodejs and moongose to work with a mongodb database. I need to read to informations basically, the field _id to get the timestamp and the field temp, one example of record:

Mongodb record example

{ _id: 57fe867e473a802218a891e0,
_etag: 57fe867e225e107c6f47dc55,
temp: 27875,
coord: [ [Object] ] }


I'm using the following code to perform the read:

Read code

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
ObjectID = require('mongodb').ObjectID;
var configDB = require('./config/database.js');
mongoose.connect(configDB.url);

mongoose.model('Temperatura',
new Schema({ time: Number, temperature: Number}),
'col');

var dados = mongoose.model('Temperatura');

dados.find({}, function(err, data)
{
if(err){
console.log(err, data, data.length);
}else{
console.log(data);
}

var Time = [];
var Temperature = [];
var Grafico = [];


for ( index in data){

var doc = data[index];
var objectId = new ObjectID(doc['_id'])
var time = objectId.getTimestamp();
console.log(doc['temp']);
var temperature = doc['temp'];

Temperature.push({"value" : temperature});
Time.push({"value" : time});

}
}).sort('-date').limit(100);


The basic problem is that only the
Time
array has values, the
Temperature
array presents undefined values, what is the code mistake?

Answer

Your mongoose model needs to match actual data in the mongodb record. Try to add temp field into your model:

mongoose.model('Temperatura',
           new Schema({ time: Number, temp: Number}),
           'col');