0

I'm trying to update almost all the fields in my schema except for _id and __v, here's the code so far:

for (var field in SchemaTarget.schema.paths) {
       if ((field !== '_id') && (field !== '__v')) {
            //all fields except _id and __v
       }
    }

now, how can I set for example: doc.field = something;? Also I've seen this: doc[field] = something, what's the difference?

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
C. Porto
  • 631
  • 3
  • 12
  • 26

2 Answers2

1
doc.field=something

It is dot notation of accessing a property of a object.'field' must be a valid JavaScript identifier, i.e. a sequence of alphanumerical characters, also including the underscore ("_") and dollar sign ("$"), that cannot start with a number. For example, object.$1 is valid, while object.1 is not.

doc[field] = something

It is bracket notation of accessing a property of a object.'field' is a string. The string does not have to be a valid identifier; it can have any value, e.g. "1foo", "!bar!", or even " " (a space).

To know in detail about those, take a look at MDN .

Asis Datta
  • 561
  • 3
  • 11
  • thanks for the explanation. Actually, I have another question, in my code I'm printing `doc.field.field2` and `doc['field.field2']` and they have different values, is this normal? shouldn't both have the same value? – C. Porto Nov 11 '14 at 11:07
  • In the bracket notation you have to use `doc['field']['field2']` – Asis Datta Nov 11 '14 at 11:17
0

There's no difference in javascript or in Mongoose for using the property or the hash accessor.

Mongoose uses the newer "get" magic property, described in detail here: https://stackoverflow.com/a/7891968/68567

You can see it if you look at the code: https://github.com/LearnBoost/mongoose/blob/master/bin/mongoose.js#L1549

Community
  • 1
  • 1
Will Shaver
  • 12,471
  • 5
  • 49
  • 64