Marco
Marco

Reputation: 2463

Can't access JSON value from data fetched from MongoDB

Goodmorning, I have the oddest thing. I hope someone can help me with this.

I'm fetching data from MongoDB (via Mongoose) Very simple result

   {
      reqts: 1469468008496
   }

I am trying to access the property reqts It's however undefined. But the result above is very clear about it's existence.

What I am doing is the following

   // This gives me the above result, but doing data.reqts gives me nothing. 
   Couple.findOne().sort('-reqts').select('reqts -_id').exec(function(err, item) {
        var data = item
        response.json(data)
    });

This gives me the object I mentioned before. If I do:

    var data = item.reqts

It gives me nothing in return (response is empty).

Hope someone can help me with this. Thanks!


UPDATED: I am now writing out to console too.

    Couple.findOne().sort('-reqts').select('reqts -_id').exec(function(err, data) {
       if (err) { response.status(500).json({error: err}) }
       else {
           console.log(typeof data)
           console.log(data)
           console.log(data.reqts)
           response.json(data)}
    });

This is what it writes to console.

object
{ reqts: 1469468008496 }
undefined

UPDATED:

This seems to explain it: Dot operator not fetching child properties of a Mongoose Document object

Upvotes: 1

Views: 973

Answers (1)

CrazyCrow
CrazyCrow

Reputation: 4235

Well as you already said - you forgot to define scheme. So next code is working

var mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/so');

var Couple = mongoose.model('Couple', { reqts: Number });

var couple = new Couple({ reqts: 1469468008496 });
couple.save(function (err) {
    if (err) {
        console.log(err);
    } else {
        Couple.findOne().sort('-reqts').select('reqts -_id').exec(function(err, data) {
            console.log(data.reqts);
        });
    }
});

But I must say there is a way around this problem. You can access field undefinied in model with data._doc so next code would work too:

var mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/so');
var treet = require('treet');

var Couple = mongoose.model('Couple', {ts: Number}); // no reqts, we even can use {}

Couple.findOne().sort('-reqts').select('reqts -_id').exec(function(err, data) {
    console.log(data._doc.reqts);
});

I think undefined fields hiding is made to make simpler sending document right to the output without additional selection of required fields.

Upvotes: 3

Related Questions