Mongoose: Arrow function not supported

Created on 19 Jan 2017  路  4Comments  路  Source: Automattic/mongoose

"mongoose": "^4.7.3",
Hey, Mongoose developer's I am using mongoose v4.7.3. I just face one issue when I am writing code in ES5 fashion
like this
ModelSchema.pre('findOneAndUpdate',(next) => { // Not working this work here just print {} empty Object console.log(this); // {} });
here this print as a empty Object

But when i write code like this then it is working

`ModelSchema.pre('findOneAndUpdate',function(next){
// well this work here
console.log(this);

// print this result
mongooseCollection:
NativeCollection {
collection: Collection { s: [Object] },
opts: { bufferCommands: true, capped: false },
name: 'hospitalreplies',
collectionName: 'hospitalreplies',
conn:
NativeConnection {
base: [Object],
collections: [Object],
models: [Object],
config: [Object],
replica: false,
hosts: null,
host: 'localhost',
port: 27017,
user: undefined,
pass: undefined,
name: 'dev',
options: [Object],
otherDbs: [],
_readyState: 1,
_closeCalled: false,
_hasOpened: true,
_listening: false,
db: [Object],
_events: [Object],
_eventsCount: 3 },
});`
can you explain why

Most helpful comment

Not mongoose docs' job to teach you rudimentary ES2015. We need to assume a certain minimal baseline of JS knowledge to keep the docs concise.

All 4 comments

This is separate from mongoose and by design.

Arrow functions do not bind this: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_binding_of_this

@cblanc is right. Arrow functions have no lexical scope:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Might be worth adding to the docs since a lot of people tend to make the assumption that arrow functions will work with a bunch of mongoose methods that they don't work with.

@cblanc and @varunjayaraman Thank you so much for your answer.Please add this on documentation

Not mongoose docs' job to teach you rudimentary ES2015. We need to assume a certain minimal baseline of JS knowledge to keep the docs concise.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

aartiles picture aartiles  路  47Comments

wshaver picture wshaver  路  50Comments

fundon picture fundon  路  42Comments

dmmalam picture dmmalam  路  93Comments

nparsons08 picture nparsons08  路  40Comments