5

Using Mongoose ORM for MongoDB

I've declared a mongoose static method like:

ConvoDataSchema.statics.randomItem = async function () { ... }

and then create a model with that

const ConvoData = mongoose.model('ConvoData', ConvoDataSchema)

but later when I want to call the method:

let convoData = await ConvoData.randomItem()

My linter is not aware that ConvoData has had this magical method patched onto it by Mongoose.

How can I declare these methods such that a Linter (TSLint / VSCode Intellisense) can properly discover these methods?

dcsan
  • 11,333
  • 15
  • 77
  • 118
  • I'm using `ESLint` and `VSCode`, it works properly for me. – Mosius May 08 '19 at 03:53
  • it works on the line you're declaring it, but in other files does ESLint know about the `ConvoData.xx()` method declaration? I think ESLint can parse the inline syntax but not recognize the object it's attached to for exports. – dcsan May 11 '19 at 07:07

4 Answers4

0

I would think that you could either tell ESLint to "ignore" lines like that, or you can get really weird and do something like:

let convoData = await ConvoDataSchema.statics.randomItem.call(ConvoData)

Sucks that neither solution is as elegant as I'm sure you were hoping for.

Pytth
  • 4,008
  • 24
  • 29
0

Looking into the documentation I found this: https://mongoosejs.com/docs/guide.html#statics

Do not declare statics using ES6 arrow functions (=>). Arrow functions explicitly prevent binding this, so the above examples will not work because of the value of this."

Can be this your problem?

geisterfurz007
  • 5,292
  • 5
  • 33
  • 54
Schwarz54
  • 964
  • 1
  • 9
  • 18
  • that might be a runtime issue. But the linter at compile time and intellisense can't really figure out those kind of issues. Maybe a true AST anaylsis linter could but i dont think ESLint is in that category. – dcsan Aug 28 '19 at 17:17
0

now I'm using typescript for most projects, and mongoose defeats getting decent intellisense because of some of the reasons above and more, my solution is not to use mongoose...

dcsan
  • 11,333
  • 15
  • 77
  • 118
-1

If declared exactly like this:

ConvoDataSchema.statics.randomItem = async function () {
const ConvoData = mongoose.model('ConvoData', ConvoDataSchema)

it won't work because the method wasn't closed. You should try closing the method. Further, what exactly is the method returning, that way, we can properly debug the method.

toonday
  • 501
  • 4
  • 13