Last Rose Studios
Last Rose Studios

Reputation: 2481

Defined variable is undefined

I am hitting up mongo (via mongoose customer.find()) and getting back something that looks like

[{ _id: 5029a09e099fb5095fdb2d73,
  clientId: 22,
  company: 'X',
  email: '[email protected]',
  firstName: 'X',
  lastName: 'Y',
  quality: 'Sold',
  address: 
   { phone: '',
     alt: '',
     street1: '',
     street2: '',
     city: '',
     state: 'Ontario',
     country: 'Canada',
     code: '' },
  comments: []
}]

Please note that this is the result from console.log directly. This is not something I am entering, this is the results from mongoDB. _id is being returned in this form by mongo and has absolutely nothing to do with the issue.

when I try

console.log(customer[0]) I get

{ _id: 5029a09e099fb5095fdb2d73,
      clientId: 22,
      company: 'X',
      email: '[email protected]',
      firstName: 'X',
      lastName: 'Y',
      quality: 'Sold',
      address: 
       { phone: '',
         alt: '',
         street1: '',
         street2: '',
         city: '',
         state: 'Ontario',
         country: 'Canada',
         code: '' },
      comments: []
    }

as expected

when I try console.log(customer[0].quality) I get undefined

when I try console.log(customer[0].email) or any of the others it works fine, and I get the expected value.

to my knowledge, quality isn't a reserved word, am I missing something?

Upvotes: 6

Views: 362

Answers (3)

Vadim Baryshev
Vadim Baryshev

Reputation: 26189

Mongoose find returns Query object. It not just plain javascript object. It inherits methods of your model, query methods, methods of Document. console.log shows you just toString method result of this object. It may be modified by getters or virtuals. _id without quotes also toString result of ObjectId class. Try access your value by customer[0].get('quality'); Or convert it to plain object via customer[0].toObject();

Upvotes: 2

jamjam
jamjam

Reputation: 3269

I took you data inserted into mongo, ran the query console.log email, quality etc.

Everything worked as expected, no undefined insight.

I'm not using Mongoose, mongojs instead so perhaps there is bug in mongoose.

Upvotes: 0

Shreedhar
Shreedhar

Reputation: 5640

this is working fine :

var customer = [{ _id: "5029a09e099fb5095fdb2d73",  clientId: 22,  company: 'X',  email: '[email protected]',  firstName: 'X',  lastName: 'Y',  quality: 'Sold',  address:    { phone: '',     alt: '',     street1: '',     street2: '',     city: '',     state: 'Ontario',     country: 'Canada',     code: '' },  comments: []}]
console.log(customer[0].quality) // it will give Sold

make _id:5029a09e099fb5095fdb2d73 to _id:"5029a09e099fb5095fdb2d73"

Upvotes: -1

Related Questions