Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dot operator not fetching child properties of a Mongoose Document object

console.log('>>>>>>user = '+ user);

outputs

>>>>>>user      = { username: 'user1',
  salt: '3303187e50a64889b41a7a1c66d3d3c10b9dec638fdd033bee1221d30d01c5e1',
  hash: 'a174c206d88bee1594bb081dbd32d53420f6ef3d6322104f3d0722d58bc8dd8d',
  _id: 52d3177481daf59c11000001,
  __v: 0 }

but

console.log('>>>>>>user.hash = '+ user.hash);

outputs

>>>>>>user.hash = undefined

What could be causing this?


Edit: Interestingly, user._id, (and only it) works.

like image 512
laggingreflex Avatar asked Jan 15 '14 04:01

laggingreflex


2 Answers

update: Solved in mongoose v3.8.19


It's totally a mongoose issue.

A solution was to not go schema-less. I was using strict: false when defining my schema (for making my database schema-less)

var Users = mongoose.model('Users', new mongoose.Schema({
    },{strict:false}));

Adding hash here solved it.

var Users = mongoose.model('Users', new mongoose.Schema({
    hash: String
    },{strict:false}));
like image 175
laggingreflex Avatar answered Nov 16 '22 16:11

laggingreflex


I believe user is an object and to access object property in JS you use . notation(Property Accessors).

And In a code posted above I can see ,ID field is missing 'quotes',

user = { username: 'user1',
         salt: '3303187e50a64889b41a7a1c66d3d3c10b9dec638fdd033bee1221d30d01c5e1',
         hash: 'a174c206d88bee1594bb081dbd32d53420f6ef3d6322104f3d0722d58bc8dd8d',
         _id: '52d3177481daf59c11000001',
         __v: 0 
     };

console.log(user.hash); // accessing hash property of `user` Object.

Working fiddle

like image 1
Deepak Ingole Avatar answered Nov 16 '22 17:11

Deepak Ingole